简体   繁体   中英

Avoid tautological-compare warning in template

I have a template class that should return different values if the (unsigned) parameter is even or odd, like in this test case:

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

This is part of a large code that uses vector instructions, so it processes more than one element at a time if possible.

Problem is, newer GCC versions emit the following warning:

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))
      |                       ~~^~~~~~~~~~

The warning is given regardless of adding the "constexpr" word.

IMHO, GCC should not emit that warning here, as the code is not always false - only in the specific template specialization.

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

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

In the latest version, gcc does not warn about this so adding an exception seems reasonable:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM