c++ - 避免模​​板中出现同义反复比较警告

标签 c++ templates

我有一个模板类,如果(无符号)参数是偶数或奇数,它应该返回不同的值,就像在这个测试用例中一样:

template <unsigned X> class t {
public:
    static int get(int *n) {
        if constexpr (1 == (X & 1))
            return n[X] + n[X-1] + t<X-2>::get(n);
        else
            return n[X] + t<X-1>::get(n);
    }
};

template <> class t<1> {
public:
    static int get(int *n) {
        return n[0] + n[1];
    }
};

template <> class t<0> {
public:
    static int get(int *n) {
        return n[0];
    }
};

int main() {
    int x[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    return t<8>::get(x);
}

这是使用 vector 指令的大型代码的一部分,因此如果可能的话,它一次处理多个元素。

问题是,较新的 GCC 版本会发出以下警告:

temp.cc: In instantiation of ‘static int t<X>::get(int*) [with unsigned int X = 8]’:
temp.cc:27:18:   required from here
temp.cc:4:25: warning: bitwise comparison always evaluates to false [-Wtautological-compare]
    4 |         if constexpr (1 == (X & 1))
      |                       ~~^~~~~~~~~~

无论添加“constexpr”一词,都会发出警告。

恕我直言,GCC 不应在此处发出该警告,因为代码并不总是错误 - 仅在特定的模板特化中。

是否有一种方法可以避免此警告,而无需根据另一个参数编写模板专门化?

最佳答案

Is there a way to avoid this warning without resorting to writing template specializations depending on another parameter?

在最新版本中,gcc does not warn about this所以添加异常(exception)似乎是合理的:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtautological-compare"
if constexpr (1 == (X & 1))
#pragma GCC diagnostic pop

关于c++ - 避免模​​板中出现同义反复比较警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65401336/

相关文章:

c++ - 可以使用 c++filt 将 demangled 名称写回 .s 文件本身吗?

c++ - 在模板类中使用标准容器迭代器

c++ - 为什么从基类而不是子类调用虚拟成员函数

c++ - 一个同时接受 std::vector 和 QVector 的函数模板?

javascript - 非模板特定的帮助程序应该位于 Meteor 中的哪里?

c++ - VB.NET 无法加载 DLL 找不到指定的模块。当dll导入时

c++ - std::shared_ptr 具有别名构造函数,是否可以检索初始指针值?

c++ - 我尝试用 C++ 编写一个 bmp 文件,但是 bmp 文件的宽度和高度似乎会影响结果,有时我会得到一个错误的 bmp 文件

php - 如何处理 Codeigniter 模板?

C++ 模板完整指南。赋值运算符