6

I am trying to make some templated version of consteval functions, I am not clear if there are any restrictions here.

template <typename T>
consteval T max(const T& a, const T& b) {
    return (a > b) ? a : b;
}

template <typename T>
consteval T mid(const T& a, const T& b, const T& c) {
    T m = max(max(a, b), c);

    if (m == a)
        return max(b, c);
    if (m == b)
        return max(a, c);

    return max(a, b);
}

consteval int imax(const int& a, const int& b) {
    return (a > b) ? a : b;
}

consteval int imid(const int& a, const int& b, const int& c) {
    int m = imax(max(a, b), c);

    if (m == a)
        return imax(b, c);
    if (m == b)
        return imax(a, c);

    return imax(a, b);
}

Most cases work fine -

std::cout << imax(1,2) << std::endl;
std::cout << imid(1,2,3) << std::endl;
std::cout << max(1,2) << std::endl;       // templated version works fine

I see compilation error for templated version again that are dependent on consteval functions. Specifically this usecase fails to compile

std::cout << mid(1,2,3) << std::endl;     // templated version fails to compile

error -

FAILED: out.p/main.cpp.o                                                                                                                                                                                   
clang++-12 -Iout.p -I. -I.. -fcolor-diagnostics -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -Wnon-virtual-dtor -Wextra -Wpedantic -std=c++2a -O0 -g -MD -MQ out.p/main.cpp.o -MF out.p/main.cpp.o.d -o out.p
/main.cpp.o -c ../main.cpp                                                                                                                                                                                 
../main.cpp:11:11: error: call to consteval function 'max<int>' is not a constant expression                                                                                                               
    T m = max(max(a, b), c);
Kamath
  • 4,461
  • 5
  • 33
  • 60
  • 3
    It's probably a clang bug. The code seems fine, and gcc is ok with it https://godbolt.org/z/aP1e5Ks5P – cigien Sep 13 '21 at 17:06
  • 4
    @cigien Perhaps regression. Clang 10.0.1 [accepts it](https://godbolt.org/z/8jhj85b38) – Ted Lyngmo Sep 13 '21 at 17:08
  • 1
    Ahh,, did not think it could be compiler issue. Thanks for pointing out. Yes indeed looks to be a regression. Compiler explorer tool seems to be very helpful. @cigien you can update it as answer for me to accept it. – Kamath Sep 13 '21 at 17:09
  • 1
    @TedLyngmo Possibly. At some point, clang parsed `consteval`, but just ignored it (or treated it as constexpr), so there's that to be considered. – cigien Sep 13 '21 at 17:10

1 Answers1

1

As pointed out by, @cigien this is indeed a clang bug. It works fine with gcc.

Kamath
  • 4,461
  • 5
  • 33
  • 60