C ++ template function for derived class with std :: is_base_of

I have a problem with creating a function that, for a given type, if it is received from another, does something, but for all the others it does something else. My code is:

class BaseClass {}; class DerivedClass : public BaseClass {}; template <typename T> void Function(typename std::enable_if<std::is_base_of<BaseClass, T>::value, T>::type && arg) { std::cout << "Proper"; } template <typename T> void Function(T && arg) { std::cout << "Improper"; } void test() { Function(DerivedClass{}); } 

For DeriviedClass and another based on BaseClass I would like to call the couting Proper function, but it is disabled by Improper . Any suggestions?

+7
c ++ c ++ 11 templates metaprogramming
source share
3 answers

As mentioned in the comments on this question, SFINAE expressions will not work the way you did it.
It should be something like this:

 template <typename T> typename std::enable_if<std::is_base_of<BaseClass, T>::value>::type Function(T && arg) { std::cout << "Proper" << std::endl; } template <typename T> typename std::enable_if<not std::is_base_of<BaseClass, T>::value>::type Function(T && arg) { std::cout << "Improper" << std::endl; } 

SFINAE expressions will enable or disable Function depending on whether BaseClass is T base. The return type is void in both cases, for it the default type is for std::enable_it if you do not define it.
Look at coliru .

There are other valid alternatives, and some of them are mentioned in other answers.

+6
source share
 template <typename T> auto Function(T && arg) -> typename std::enable_if<std::is_base_of<BaseClass, T>::value>::type { std::cout << "Proper"; } template <typename T> auto Function(T && arg) -> typename std::enable_if<!std::is_base_of<BaseClass, T>::value>::type { std::cout << "Improper"; } 

wandbox example

+3
source share
 #include <typeinfo> #include <iostream> class BaseClass {}; class DerivedClass : public BaseClass {}; class OtherClass {}; template <typename T,typename = typename std::enable_if<std::is_base_of<BaseClass, T>::value, T>::type> void Function(T && arg) { std::cout << "Proper" << std::endl; } void Function(...) { std::cout << "Improper"<< std::endl; } int main() { Function(DerivedClass{}); Function(BaseClass{}); Function(OtherClass{}); } 
+3
source share

All Articles