Going from a basic CRTP with the core concept being the this pointer cast -
#include "stdafx.h"
#include <iostream>
using namespace std;
template<class T>
class A
{
public:
void a0(){ static_cast<B*>(this)->a2(); }
void a2(){ cout << "a2 base" << endl; }
};
class B: public A<int>//<int>
{
public:
void a1(){ a0(); }
void a2(){ cout << "a2 derived" << endl; }
};
int _tmain(int argc, _TCHAR* argv[])
{
B b;
b.a1();
return 0;
}
why does the cast fail if A is no template? (MSVC: error C2440: 'static_cast' : cannot convert from 'A *const ' to 'B *')
Or the other way around, why does it work if it is a template.
class B;
class A
{
public:
void a0(){ static_cast<B*>(this)->a2(); }
void a2(){ cout << "a2 base" << endl; }
};
class B: public A
{
public:
void a1(){ a0(); }
void a2(){ cout << "a2 derived" << endl; }
};
Probably to do with the timing of template instantiation, but I'm curious about the details.