Try this:
struct Base { virtual ~Base() {} };
struct MyClass : public Base {};
template <class T> MyClass* BaseToMyClass(T p) {
int x[-(int)sizeof(T)];
return 0;
}
template <> MyClass* BaseToMyClass(Base* p) {
printf("1\n");
MyClass* pRes = dynamic_cast<MyClass*>(p);
assert(pRes != NULL);
return pRes;
}
If the function is called with Base*, the 1st specialization will be used. If it is called with MyClass*, the generic version will be used. Since an array cannot have negative size, this will cause a compile-time error, which can be traced back to the point of instantiation.
The sizeof(T) is to ensure the error is shown only at instantiation time.
Note that this method is not suitable if Base has any other subclasses you want to pass.
Example usage:
int main () { // 22
MyClass p; // 23
Base q; // 24
BaseToMyClass(&q); // 25
BaseToMyClass(&p); // 26
} // 27
Results in
x.cpp: In function 'MyClass* BaseToMyClass(T) [with T = MyClass*]':
x.cpp:26:22: instantiated from here
x.cpp:11:27: error: creating array with negative size ('-0x00000000000000008')
Note that it cannot detect what the pointer is new-ed with. For instance, in
int main () {
Base* p = new Base;
Base* q = new MyClass;
BaseToMyClass(p);
BaseToMyClass(q);
delete p;
delete q;
}
the program will be compiled successfully.