Reputation: 7809
I can specialize a template:
template <class T> T f(T x){ ... }
template <> int f(T x) { ... }
As far as i know, I can not specialize it for a whole set of T? For example for several numerical types, like:
template <class T> T f(T x){ ... }
template <> (int, double) f(T x) { ... }
The round parantheses (int, double) would then represent a whole set of types.
Upvotes: 1
Views: 156
Reputation: 55395
I'd write a type trait class for convenience (because there isn't one in standard library) to check if a type is the same as one of a list of types:
template<typename T, typename U, typename... Ts>
struct is_any_of : is_any_of<T,Ts...> { };
template<typename T, typename... Ts>
struct is_any_of<T,T, Ts...> : std::true_type { };
template<typename T, typename U>
struct is_any_of<T,U> : std::false_type { };
Now you can use it with enable_if
to conditionaly enable the overload (not specialization):
template <class T> T f() { /* ... */ }
// unlike normal functions, function templates can be overloaded on return types!
template<typename T>
std::enable_if<
is_any_of< T, int, double, float, short, std::complex<double> >::value,
T
>::type
f() { /* ... */ }
This unfortunately means that the call to f
is ambiguous if T
is found in the list of types. If you really need two overloads you can fix this by doing the same thing with the other overload, only with the condition of enable_if
reversed (efectively doing "disable_if").
Upvotes: 3