c++ - 删除模板参数的 g++ 警告

标签 c++ templates g++

我有一个简单的类:

template<size_t N, typename T>
class Int
{
    bool valid(size_t index) { return index >= N; }
    T t;
}

如果我将此类的实例定义为:

Int<0, Widget> zero;

我收到 g++ 警告:

warning: comparison is always true due to limited range of data type

我尝试这样做,但我无法弄清楚如何使用非类型模板参数部分特化一个函数。 看起来可能无法在 g++ 中禁用此警告。隐藏此警告或编写此方法使其在 N==0 时始终返回 true 的正确方法是什么?

谢谢!

最佳答案

所以,我想出了以下解决方案:

template<size_t N>
bool GreaterThanOrEqual(size_t index)
{
    return index >= N;
}

template<>
bool GreaterThanOrEqual<0l>(size_t index)
{
    return true;
}

所以现在,类看起来像:

template<size_t N, typename T>
class Int
{
    bool valid(size_t index) { return GreaterThanOrEqual<N>(index); }
    T t;
}

当然,我收到一个未使用的参数警告,但有办法解决这个问题......

这是一个合理的解决方案吗?

关于c++ - 删除模板参数的 g++ 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4630805/

相关文章:

c++ - Boost.Spirit 入门指南?

c++ - 获取不带模板参数的对象类型

c++ - 如何使用 cmake 正确链接库(.so y .a)

c++ - 在 g++ 中使用依赖项的问题

c++ - 在一个 GPU 上运行的多个深度学习框架导致 CUDNN_STATUS_BAD_PARAM

c++ - 使用 unordered_map 移动构造函数

c++ - SDL_FillRect 不绘图?

c++ - 添加参数后“模板参数推导/替换失败”

c++ - 将值传递给功能模板的最佳方法

c++ - g++ 如何解决警告 "used but never defined"? (不是静态的或内联的)