Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid tautological-compare warning in template

Tags:

c++

templates

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?

like image 658
dmsc Avatar asked Mar 11 '26 07:03

dmsc


1 Answers

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
like image 104
Ted Lyngmo Avatar answered Mar 12 '26 19:03

Ted Lyngmo