簡體   English   中英

避免模板中的重言式比較警告

[英]Avoid tautological-compare warning in template

我有一個模板 class 如果(無符號)參數是偶數或奇數,它應該返回不同的值,就像在這個測試用例中一樣:

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);
}

這是使用向量指令的大型代碼的一部分,因此如果可能,它一次處理多個元素。

問題是,較新的 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 不應在此處發出該警告,因為代碼並不總是錯誤的-僅在特定的模板專業化中。

有沒有辦法避免這個警告而不依賴於另一個參數編寫模板特化?

有沒有辦法避免這個警告而不依賴於另一個參數編寫模板特化?

在最新版本中, gcc 沒有對此發出警告,因此添加異常似乎是合理的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM