I need to create a template function like this:
template
void foo(T a)
{
if (T is a subclass of class Bar)
do this
else
d
I would use std::is_base_of
along with local class as :
#include //you must include this: C++11 solution!
template
void foo(T a)
{
struct local
{
static void do_work(T & a, std::true_type const &)
{
//T is derived from Bar
}
static void do_work(T & a, std::false_type const &)
{
//T is not derived from Bar
}
};
local::do_work(a, std::is_base_of());
}
Please note that std::is_base_of
derives from std::integral_constant
, so an object of former type can implicitly be converted into an object of latter type, which means std::is_base_of
will convert into std::true_type
or std::false_type
depending upon the value of T
. Also note that std::true_type
and std::false_type
are nothing but just typedefs, defined as:
typedef integral_constant true_type;
typedef integral_constant false_type;