I'm trying to restrict the template type of a function to a specific class and their subclasses at compile time. To accomplish this, I'm using the type traits std::enable_if_t and std::is_base_of like this:
template <typename T = std::enable_if_t<std::is_base_of<A, T> > >
But the template still compiles with types which are not part of the inheritance hierarchy (i.e. int). Below is an MCVE of the problem:
class A {
public:
A(float a) : a(a) {}
float a;
};
class B : public A{
public:
B(float a) : A(a) {}
};
template <typename T = std::enable_if_t<std::is_base_of<A, T> > >
void templateFunction(T a) {
}
int main() {
templateFunction<A>(A(1.0f)); // OK -> std::is_base_of<A, A>
templateFunction<B>(B(1.0f)); // OK -> std::is_base_of<A, B>
templateFunction<int>(1); // Should not compile! int is not a subclass of A -> std::is_base_of<A, int>
return 0;
}
This compiles under Visual Studio 2017 without any error, but the last instantiation of the template function should not compile in my understanding. Is there any problem in my usage of the type traits or is there a problem with Visual Studios SFINAE implementation?