Inheritance with CRTP
I have these 3 classes.
class A
{
public:
virtual void Func() = 0;
};
template<class T>
class B : public A
{
public:
void Func()
{
cout << "In B" << endl;
开发者_开发技巧 static_cast<T*>(this)->Func();
}
};
class C : public B<C>
{
public:
void Func()
{
cout << "In C" << endl;
}
};
And, I do this:
int main(int argc, char **argv)
{
A *a = new C;
a->Func();
return 0;
}
And it prints : "In C".
If I do this,
int main(int argc, char **argv)
{
B<C> *a = new C;
a->Func();
return 0;
}
It again prints "In C"
What is going on?
You're calling a virtual member function of a class C object who has overloaded this function. It calls the function in class C.
Furthermore, this is not CRTP as the templated class B does not inherit from the class template parameter.
Func
is virtual, a
is a pointer to an instance of C
, so C
's version of Func
is called.
The code is not complete, add #include and "using namespace std;". More importantly, you get the desired behaviour by removing the virtual function declaration in A. In general, the main reason to use CRTP is to let the template know the type it receives and avoid doing a virtual call (or better, avoid making the method virtual).
template <typename T>
class ClassUsingSomething {
public:
void method1() {
// I need to call method2, I do this by casting, so it doesn't need to be virtual.
static_cast<T *>(this)->method2();
}
};
class A: public ClassUsingSomething<A> {
public:
void method2() {
//do something
}
};
精彩评论