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