Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

enums

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?

like image 312
Will Crawford Avatar asked Jun 29 '16 09:06

Will Crawford


People also ask

Can enum be bool?

if you need your enum to contain boolean data in addition to the enum constant's type value, you could add a simple attribute to your enum, taking a boolean value. Then you can add an extension method for your enum that fetches the attribute and returns its boolean value.

What is enum in C++ with example?

Enumeration is a user defined datatype in C/C++ language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration. The following is the syntax of enums. enum enum_name{const1, const2, ....... };


1 Answers

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.

like image 190
MaciekGrynda Avatar answered Nov 15 '22 03:11

MaciekGrynda