基于“签名”的部分模板专门化整数类型? [英] Partial template specialization based on "signed-ness" of integer type?

查看:107
本文介绍了基于“签名”的部分模板专门化整数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定:

template<typename T>
inline bool f( T n ) {
  return n >= 0 && n <= 100;
}   

使用 unsigned type生成警告:

When used with an unsigned type generates a warning:

unsigned n;
f( n ); // warning: comparison n >= 0 is always true

有没有聪明的方法当 T 无符号 n> = 0 > type?我尝试添加一个部分模板专门化:

Is there any clever way not to do the comparison n >= 0 when T is an unsigned type? I tried adding a partial template specialization:

template<typename T>
inline bool f( unsigned T n ) {
  return n <= 100;
}   

但gcc 4.2.1不喜欢。 (我并不认为种类的部分模板专业化是合法的。)

but gcc 4.2.1 doesn't like that. (I didn't think that kind of partial template specialization would be legal anyway.)

推荐答案

您可以使用 enable_if is_unsigned 类型特征:

You can use enable_if with the is_unsigned type trait:

template <typename T>
typename std::enable_if<std::is_unsigned<T>::value, bool>::type f(T n)
{
    return n <= 100;  
}

template <typename T>
typename std::enable_if<!std::is_unsigned<T>::value, bool>::type f(T n)
{
    return n >= 0 && n <= 100;  
}

您可以找到 enable_if std :: tr1 中的<$ c $>和 is_unsigned 命名空间,如果你的编译器分别支持C ++ 0x或TR1。否则,Boost具有类型traits库的实现, Boost.TypeTraits enable_if 的boost实现有点不同; boost :: enable_if_c 类似于TR1和C ++ 0x enable_if

You can find enable_if and is_unsigned in the std or std::tr1 namespaces if your compiler supports C++0x or TR1, respectively. Otherwise, Boost has an implementation of the type traits library, Boost.TypeTraits. The boost implementation of enable_if is a little different; boost::enable_if_c is similar to the TR1 and C++0x enable_if.

这篇关于基于“签名”的部分模板专门化整数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆