I have the following template class and a (global) variable of its type:
template <typename ClassT>
struct ClassTester : public ClassT {
typedef ClassT type;
};
ClassTester<int> *aaa; // No error here
I would expect a compilation error because int cannot be derived from, but this compiles fine under Visual C++ 2010.
If I remove the pointer, I get the expected compilation error (int cannot be derived from):
ClassTester<int> bbb; // Error here
I wanted to use this class for SFINAE testing whether the given type is a class that can be derived from:
template <typename T>
struct CanBeDerivedFrom {
template <typename C>
static int test(ClassTester<T> *) { }
template <typename>
static char test(...) { }
static const bool value = (sizeof(test<T>(0)) == sizeof(int));
};
This, however, always reports true, even for primitive types such as int because of the above reason. Is this an expected/valid behavior of C++?
I think it’s not possible entirely to get a
classwhich is derivable through SFINAE (which includes also the cases offinal classin C++11). The best thing which can be done is to have a SFINAE for finding if a type is aclassand rely upon that.This metaprogram will find if the given type is
class/unionor not. demo.