Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

c++ - Why doesn't the compiler generate compile errors if an incorrect argument type is passed to a struct initialiser list?

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.)
question from:https://stackoverflow.com/questions/37191679/why-doesnt-the-compiler-generate-compile-errors-if-an-incorrect-argument-type-i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...