为什么如果将不正确的参数类型传递给struct初始化列表,编译器是否会生成编译错误? [英] Why doesn't the compiler generate compile errors if an incorrect argument type is passed to a struct initialiser list?

查看:91
本文介绍了为什么如果将不正确的参数类型传递给struct初始化列表,编译器是否会生成编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个结构,它有一个构造函数:

  struct MyStruct 
{
MyStruct (const int value)
:value(value)
{
}
int value;
};

和以下对象:

  int main()
{
MyStruct a(true);
MyStruct b {true};
}

但我没有收到任何编译错误,无论是与MVS2015或Xcode 7.3 .1。


  1. 为什么我没有收到任何编译错误?

  2. 编译器帮助我检测这个? (最初,结构体被写成具有 bool 数据,但是在一段时间后,代码改变了,并且 bool c $ c> int 和几个错误。)


解决方案

p> A bool 可以以值保留的方式隐式转换为 int 。唯一不允许的大括号初始化转化是 缩小转化(例如

如果你想确保你的类是可构造的只有 c> c>, c> c>

  struct MyStruct 
{
explicit MyStruct(int i):value(i){}

template< typename T>
MyStruct(T t)= delete;

int value;
};

这里, MyStruct {true} code> MyStruct(false)将调用 MyStruct :: MyStruct< bool> ,它被定义为删除,形成。



这个优点 static_assert 是所有的类型traits实际上会产生正确的值。例如, std :: is_constructible< MyStruct,bool> std :: false_type


I have defined a struct, which has a constructor:

struct MyStruct
{
    MyStruct(const int value)
        : value(value)
    {
    }
    int value;
};

and the following objects:

int main()
{
    MyStruct a (true);
    MyStruct b {true};
}

But I haven't received any compile errors, either with MVS2015 or Xcode 7.3.1.

  1. Why am I not getting any compile errors?
  2. How do I make the compiler help me detect this? (Initially, the struct was written to have bool data, but after some time, code changed and bool became int and several bugs were introduced.)

解决方案

A bool can be implicitly converted to an int in a way that's value preserving. The only disallowed conversions with brace initialization are narrowing conversions (e.g. the reverse bool{42}).

If you want to ensure that your class is constructible only with int, then the direct way is simply to delete all the other constructors:

struct MyStruct
{
    explicit MyStruct(int i) : value(i) { }

    template <typename T>
    MyStruct(T t) = delete;

    int value;
};

Here, MyStruct{true} and MyStruct(false) will yield calls to MyStruct::MyStruct<bool>, which is defined as deleted and hence is ill-formed.

The advantage of this over static_assert is that all the type traits will actually yield the correct values. For instance, std::is_constructible<MyStruct, bool> is std::false_type.

这篇关于为什么如果将不正确的参数类型传递给struct初始化列表,编译器是否会生成编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆