I am working on a project where we had a standard enum like this:
enum Services {
RequestShower = 611,
RequestBath = 617,
RequestShave = 612,
RequestHaircut = 618
};
But my boss was saying that the latest C++ standard doesn’t regard an enum to be equivalent to an int so instead proposed using a class a bit like this:
class VatelPrivateService {
public:
static const short
RequestShower = 611,
RequestBath = 617,
RequestShave = 612,
RequestHaircut = 618;
static const char* getName(int val);
};
ostream operator<<(ostream& os, VatelPrivateService& service);
Well, I tried to implement like this:
const char* VatelPrivateService::getName(int id)
{
#define CASE_NM(rq) case rq: return #rq
switch(id)
{
CASE_NM(RequestShower);
CASE_NM(RequestBath);
CASE_NM(RequestShave);
CASE_NM(RequestHaircut);
}
#undef CASE_NM
return "";
}
ostream& operator<<(ostream& os, const VatelPrivateService& service)
{
os << VatelPrivateService::getName(service);
return os;
}
and call it like this:
cout << "item: " << VatelPrivateService::RequestShower << endl;
But the code above doesn’t compile – get :
error C2664: ‘VatelPrivateService::getName’ : cannot convert parameter 1 from ‘const VatelPrivateService’ to ‘int’
Hopefully you can see my intent. how do I fix this?
Angus
The specification of
enumhas not changed: an enumerator is still implicitly convertible to its underlying integral type.C++11 adds a new concept,
enum class, which is a “strongly typed and scoped enum.” This new kind of enumeration does not allow its enumerators to be implicitly converted to the underlying integral type (though, you can explicitly coerce the conversion usingstatic_cast).If you want to write your own scoped enumeration that provides semantics and behavior similar to
enum classbut is usable on compilers that do not supportenum class, you should read Howard Hinnant’s answer to this other question, wherein he provides a working example.