由于无符号,在模板化方法中删除警告

use*_*462 4 c++ templates compiler-warnings c++03

我找到了一些模板化的代码,在某些时候执行以下检查:

template<class IntegralType>
void randomFunction(IntegralType t)
{
    ...
    if (t < 0)
    ...
}
Run Code Online (Sandbox Code Playgroud)

代码的概念t是整数类型(有符号或无符号).无论签名如何,代码都可以正常工作,但编译器会发出警告,因为在unsigned整数的情况下,检查将始终为true.

在C++ 03中有没有办法修改代码以摆脱警告而不抑制它?我正在考虑T以某种方式检查签名,不知道它是否可能.

我知道C++ 11,is_signed但我不确定它是如何在C++ 03中实现的.

Jar*_*d42 6

使用Tag调度和特征:

template <typename T>
bool is_negative(T t, std::true_type)
{
    return t < 0;
}
template <typename T>
bool is_negative(T t, std::false_type)
{
    return false;
}

template<class IntegralType>
void randomFunction(IntegralType t)
{
    ...
    if (is_negative(t, std::is_signed<IntegralType>::type())
    ...
}
Run Code Online (Sandbox Code Playgroud)

std::is_signed 可以用C++ 03实现.