C++ template function for derived class with std::is_base_of
As mentioned in the comments to the question, SFINAE expressions won't work the way you did it.
It should be instead 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 the fact that BaseClass
is base of T
. Return type is void
in both cases, for it's the default type for std::enable_it
if you don't define it.
See it on coliru.
Other valid alternatives exist and some of them have been mentioned in other answers.
#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{});
}
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