You could use std::enable_if
and do something like this to obtain exactly what you want:
#include <iostream>
#include <type_traits>
template<class T>
class example
{
private:
T data;
public:
void print()
{
std::cout << " hello " << std::endl;
}
template<class U = T // make the function templated on U, but with default type T
, typename std::enable_if<std::is_integral<U>::value>::type* = nullptr // enable only for when U (T) is an integral type
>
void foo()
{
std::cout << " I will only compile when T is an integral type " << std::endl;
}
};
int main()
{
example<int> integer_example;
integer_example.print();
integer_example.foo(); // <--- compiles fine as int is integral
example<double> double_example;
double_example.print();
//double_example.foo(); // <--- will not compile
return 0;
}
In the std::enable_if
you can also put std::is_same<U,int>::value
instead of std::is_integral<U>::value
to only allow the function only to be used for int
and not other integral types.