Will Crawford
Will Crawford

Reputation: 261

constructing enum with underlying "bool" type from a boolean?

If I define an enum like so:

enum Foo : bool { Left = false, Right = true };

then try to construct one from a boolean like so:

int main (int ac, const char **av) {
    Foo foo ( ac > 1 );
    cout << boolalpha << bool(foo) << endl;
    return 0;
}

it fails, but works with an extra constructor like so:

Foo foo ( Foo( ac > 1 ) );

Why is this? I thought Foo foo (...) was an explicit constructor call?

Upvotes: 9

Views: 10936

Answers (2)

PodHunter
PodHunter

Reputation: 74

Foo foo ( ac > 1 ); That's a case of the C++ most vexing parse. It's a function declaration that does nothing.

Upvotes: 3

MaciekGrynda
MaciekGrynda

Reputation: 703

I don't think you can do this:

Foo foo ( ac > 1 );

Suppose you define Foo enum as:

enum Foo : bool { Left = false };

What would happen if you called:

Foo foo(true);

You don't have appropriate enum value for what you want to initialize with.

Upvotes: 3

Related Questions