基于“签名”的部分模板专门化整数类型? [英] Partial template specialization based on "signed-ness" of integer type?
问题描述
给定:
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屋!