[英]Specialize template for a set of values
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? 据我所知,我不能专门针对整个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. 然后,圆括号(int,double)将代表一整套类型。
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): 现在,您可以将其与
enable_if
一起使用,以有条件地启用重载 ( 不是专门化):
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. 不幸的是,这意味着如果在类型列表中找到
T
则对f
的调用是不明确的。 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"). 如果您确实需要两个重载,则可以通过对另一个重载执行相同的操作来解决此问题,仅在
enable_if
的条件相反的情况下(有效地执行“ disable_if”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.