C++11 Scoped Enums

Hi Guys,
Can you please point out what is wrong with the code below? I keep getting this error on Eclipse June (GCC4.6.2 with -std=c++0x):

cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’

#include <iostream>
using namespace std;

int main()
{
enum class StatusA : int {STARTED, FINISHED};
enum class StatusB : int {STARTED, COMPLETED};

StatusA ProgramStatusA = StatusA::STARTED;
StatusB ProgramStatusB = StatusB::STARTED;

cout<<ProgramStatusA<<endl; /ERROR!
cout<<ProgramStatusB<<endl; /ERROR!
}
Implicit type conversion (coercion) to and from type int is not possible with scoped enumerations. Your source code will compile if you explicitly cast the variable to type int with the static_cast operator.

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
 
int main()
{
       enum class StatusA : int {STARTED, FINISHED};
       StatusA ProgramStatusA = StatusA::STARTED;
       cout<<static_cast<int>(ProgramStatusA)<<endl;
}
Last edited on
Thank you Vivre.

As you know the code is working perfect now. I still don't get why I have to cast to int when I already specified that the enum identifier type is int during the enum declaration. Regardless of what type the identifier is, why does cout have issues with outputting it? Should cout not just output whatever ProgramStatusA is regardless of it's type? Why does cout "care"?

P.s. I am learning from the Deitel How to Program 9th Edition (updated for C++11) and it only gives a brief mention of scoped enums with no mention of having to perform explicit type conversion (by the way, I thought that specifying the enum type as int during the declaration was explicit!).

Thanks for you help!
enum class do two things.
1. It forces you do access the enumerators by prefixing the enum name. EnumName::enumerator
2. It prevents implicit conversions to the underlying type.

It is a bit sad that we can't get one without the other.

Specifying the underlying type can be done for all enums, not just enum class.
Last edited on
Topic archived. No new replies allowed.