There are two ways to do this.
Firstly, using the parameter of the hidden template template that uses std::enable_if
with the condition std::is_base_of<A, T>::value
as. If the last expression is false
, then the nested type
does not exist in std::enable_if
. If you used this with overloaded functions, SFINAE means that “replacement failure is not an error,” and the overload in question will be removed from the set of viable functions. Although in this situation there is no other class template to match your call, and then you will get a compile time error.
SFINAE is a very delicate mechanism and is easily mistaken. For instance. if you have several class specializations with different SFINAE conditions, you must make sure that they all do not overlap, or you get ambiguity.
Secondly, you can make simple static_assert
with std::is_base_of<A,T>::value
inside the class body. The advantage of this method is that you also provide a more readable error message than the SFINAE method. The downside is that you always get an error message, and you cannot silently disable this particular template and choose another one. But overall, I think this method is recommended in your case.
As noted in the comments, you can use either the decent C ++ 11 compiler (VC ++ 2010 or later, gcc 4.5 or later), or the Boost or TR1 libraries to get <type_traits>
functionality. Note, however, that std::is_base_of<A, A>::value
evaluates to true
, but the old boost::is_base_of<A, A>::value
used to check for false
.
source share