I need to create a template function like this:
template<typename T>
void foo(T a)
{
if (T is a subclass of class Bar)
do this
else
do something else
}
I can also imagine doing it using template specialization ... but I have never seen a template specialization for all subclasses of a superclass. I don't want to repeat specialization code for each subclass
I like this clear style:
You can do what you want but not how you are trying to do it! You can use
std::enable_if
together withstd::is_base_of
:Since this stuff gets more wide-spread, people have discussed having some sort of
static if
but so far it hasn't come into existance.Both
std::enable_if
andstd::is_base_of
(declared in<type_traits>
) are new in C++2011. If you need to compile with a C++2003 compiler you can either use their implementation from Boost (you need to change the namespace toboost
and include"boost/utility.hpp"
and"boost/enable_if.hpp"
instead of the respective standard headers). Alternatively, if you can't use Boost, both of these class template can be implemented quite easily.I know this question has been answered but nobody mentioned that std::enable_if can be used as a second template parameter like this:
I would use
std::is_base_of
along with local class as :Please note that
std::is_base_of
derives fromstd::integral_constant
, so an object of former type can implicitly be converted into an object of latter type, which meansstd::is_base_of<Bar,T>()
will convert intostd::true_type
orstd::false_type
depending upon the value ofT
. Also note thatstd::true_type
andstd::false_type
are nothing but just typedefs, defined as: