为什么如果将不正确的参数类型传递给struct初始化列表,编译器是否会生成编译错误? [英] Why doesn't the compiler generate compile errors if an incorrect argument type is passed to a struct initialiser list?
问题描述
我定义了一个结构,它有一个构造函数:
struct MyStruct
{
MyStruct (const int value)
:value(value)
{
}
int value;
};
和以下对象:
int main()
{
MyStruct a(true);
MyStruct b {true};
}
但我没有收到任何编译错误,无论是与MVS2015或Xcode 7.3 .1。
- 为什么我没有收到任何编译错误?
- 编译器帮助我检测这个? (最初,结构体被写成具有
bool
数据,但是在一段时间后,代码改变了,并且bool
c $ c> int 和几个错误。)
p> A bool
可以以值保留的方式隐式转换为 int
。唯一不允许的大括号初始化转化是 缩小转化(例如
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.
- Why am I not getting any compile errors?
- 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 andbool
becameint
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屋!