I get the following error with VS2008: Conversion to enumeration type requires an explicit cast (static_cast, C-style cast or function-style cast)
When casting a down casting a ClassA to ClassA_1 and ClassA_1 is a templated class that received an enum for parameter such as:
THIS IS AN EDIT OF MY QUESTION WHICH RE-USE AN ANSWER BELOW BUT MODIFED TO CAUSE THE PROBLEM I AM HAVING, here we go:
Ok i have been able to reproduce my error with this code:
class ClassA
{
public:
virtual ~ClassA(){}
};
template <class Param1 = void*> class ClassB : public ClassA {
public:
//constructor
ClassB(Param1 p1 = NULL)
{
_p1 = p1;
}
//ClassB(const ClassB<Param1>& ref);
Param1 _p1;
~ClassB(){}
};
enum lolcakes {
cakeisalie,
};
ClassA* ptr = new ClassB<lolcakes>(lolcakes::cakeisalie);
ClassB<lolcakes>* a1 = (ClassB<lolcakes>*)ptr;
There are so many syntax errors here, I don’t know where to begin. Next time, please post the actual code you used.
For starters, I’m assuming that you meant to write this:
In other words,
ais a pointer and its type isClassA<myenum>*, not merelyClassA(and we’ll ignore the missing argument to the constructor).Now, your cast syntax is wrong in both cases. The parentheses need to go around the type only. But better use a
static_castanyway:This works.
UPDATE After question edit:
The important error is in this line:
you cannot use
NULLas the default parameter since yourParam1type is not a pointer – it’s an enum (strictly speaking this should work sinceNULLis defined as being equal to0in C++, but it’s a logical error nonetheless). Instead of making the parameter optional, a better alternative would be to overload the constructor. Alternatively, the following also works:This uses the default value for the type
Param1.There’s an additional error in the code:
Enum constants don’t work like that in C++: They don’t create an own namespace, hence their usage cannot be qualified. Instead, omit the enum’s name:
Finally, please don’t use C-style casts, ever. Always replace them with the appropriate C++-style casts. In your case, replace
with