I am trying to define a class template with non-templated member function f()
,
where f() is allowed to call only when the template agument of the class is int
.
#include <type_traits>
using namespace std;
template<typename T>
struct MyClass
{
T f()
{
typename enable_if< is_same<T,int>::value >::type();
return 0;
};
};
int main()
{
MyClass<int> x;
MyClass<double> y;
x.f();
y.f(); // generates compile-time error
}
It works, but is it a good idea, or it is better to use the regular solutions ?
std::enable_if to conditionally compile a member function
usage of enable_if for non-templated member function
Selecting a member function using different enable_if conditions
Are there alternative methods ?
[EDIT]
The problem is that if I use the standard technique, the templated function call via y.f<int>()
will be allowed in the following code:
#include <type_traits>
using namespace std;
template<typename T>
struct MyClass
{
template<typename U = T>
typename enable_if< is_same<U,int>::value, T >::type f()
{
T a = 1;
return a;
};
};
int main()
{
MyClass<int> x;
MyClass<double> y;
x.f();
y.f<int>(); // does not generate compile-time error
y.f(); // generates compile-time error
}