specification of function templates
-
28-10-2019 - |
سؤال
I would like to create a function template where the class T is limited to only derived classes of a special base class T_base. What is the efficient way to accomplish this? Thanks for your help!
المحلول
You can use type traits and SFINAE
template<typename T,
bool[std::is_base_of<T_base, T>::value] = nullptr>
void f(T const&);
C++03 version that also works for C++11
template<typename T>
typename boost::enable_if< boost::is_base_of<T_base, T> >::type
f(T const&);
There is the C++11 version of moving the enable_if
into the template parameter list, using a default argument
template<typename T,
typename = typename std::enable_if<
std::is_base_of<T_base, T>::value>::type>
void f(T const&);
Sadly you then cannot overload f
if the only difference of your other overload is the SFINAE string (i.e the default argument), because the default argument is not part of the signature of a function template. But the type of the template parameters themselfs are (these rules are just like for normal function parameters).
نصائح أخرى
C++0x has std::enable_if
; if your compiler doesn't yet support it, there's boost::enable_if
.
For example if the signature would be template<typename T> int f(T&)
, you'd use
template<typename T>
std::enable_if<std::is_base_of<T_base, T>::value, int>::type f(T&);
The simplest way I can think of would be something like this:
template<class T>
void someFunc(T arg)
{
dynamic_cast<BaseClass>(arg); // will throw an exception if not castable to base class
// continue...
}