I have a class with template method that the parameter defines the return type. The default constructor for everything else is ok, but for bool I would like the method to return true. I am trying to specialize it as the following code, but this does not compile.
class Foo {
template <class T>
T method() {
...
return T();
}
template<>
bool method() {
...
return true;
}
};
How I can achieve this?
You cannot specialize inside a class scope. According to the C++ standard,
14.7.3/2 An explicit specialization shall be declared in a namespace enclosing the specialized template.
Therefore you should specialize the template member function at namespace scope,
template<> // this should be outside the primary template class definition
bool Foo::method() {
return true;
}
You can use SFINAE to achieve the desired effect, which technically turns the "specialization" (which is not possible as the other answer explained) into an overload:
template <class T>
typename std::enable_if<
! std::is_same< T, bool >::value,
T
>::type
method() {
...
return T();
}
template <class T>
typename std::enable_if<
std::is_same< T, bool >::value,
T
>::type
method() {
...
return true;
}
The above is C++11, with C++14 you can even use std::enable_if_t to make it shorter.
Live example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With