如何为不同类型(某种伪语言)创建具有不同行为的模板,例如:
template <typename T>
T GetRand(T param)
{
if (T is of any real type) {
// use uniform_real_distribution
}
if (T is of any integer type) {
// use uniform_int_distribution
}
if (T is of any other type) {
// do nothing
}
}
那些怎么写if T is of xxx type
?
如果可以的话,我使用C ++ 11。
您可以在的每个重载上使用SFINAE GetRand
,但有时使用tag-dispatch变得容易得多。我们将为每个潜在的重载选择一个唯一的类型(“T
是任何实数类型”,“T
是任何整数类型”,“其他”),并构造正确的类型作为辅助函数的第二个参数。
首先,我们必须选择正确的标签:
struct integral_tag{};
struct floating_tag{};
struct other_tag{};
template <typename T>
struct get_tag
: std::conditional<
std::is_integral<T>::value,
integral_tag,
typename std::conditional<
std::is_floating_point<T>::value,
floating_tag,
other_tag>::type
>
{ };
template <typename T>
using get_tag_t = typename get_tag<T>::type;
然后,我们使用该类型特征进行转发:
template <typename T>
T GetRand(T param) {
return GetRand(param, get_tag_t<T>{} );
}
然后只写那些重载:
template <typename T>
T GetRand(T param, integral_tag ) { ... };
template <typename T>
T GetRand(T param, floating_tag ) { ... };
template <typename T>
T GetRand(T param, other_tag ) { ... };
就个人而言,我认为这更容易阅读。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句