C++ enum casting and templates
I get the following error with VS2008: Conversion to enumeration type requires an expl开发者_运维知识库icit 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:
ClassA<myenum>* a = new ClassA_1<myenum>();
In other words, a
is a pointer and its type is ClassA<myenum>*
, not merely ClassA
(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_cast
anyway:
ClassA_1<myenum>* a1 = static_cast<ClassA_1<myenum>*>(a);
This works.
UPDATE After question edit:
The important error is in this line:
ClassB(Param1 p1 = NULL)
you cannot use NULL
as the default parameter since your Param1
type is not a pointer – it’s an enum (strictly speaking this should work since NULL
is defined as being equal to 0
in 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:
ClassB(Param1 p1 = Param1())
This uses the default value for the type Param1
.
There’s an additional error in the code:
ClassA* ptr = new ClassB<lolcakes>(lolcakes::cakeisalie);
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:
ClassA* ptr = new ClassB<lolcakes>(cakeisalie);
Finally, please don’t use C-style casts, ever. Always replace them with the appropriate C++-style casts. In your case, replace
ClassB<lolcakes>* a1 = (ClassB<lolcakes>*)ptr;
with
ClassB<lolcakes>* a1 = boost::polymorphic_downcast<ClassB<lolcakes>*>(ptr);
// or
ClassB<lolcakes>* a1 = static_cast<ClassB<lolcakes>*>(ptr);
class ClassA
{
virtual ~ClassA(){}
};
template <class Param1> class ClassB : public ClassA {
public:
//constructor
ClassB(Param1 p1)
: _p1(p1) {}
ClassB(const ClassB<Param1>& ref);
Param1 _p1;
~ClassB(){}
};
enum lolcakes {
cakeisalie,
};
ClassA* ptr = new ClassB<lolcakes>(lolcakes::cakeisalie);
ClassB<lolcakes> a = (ClassB<lolcakes>(lolcakes::cakeisalie));
ClassB<lolcakes> a1 = a;
精彩评论