Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

consteval with templates possible? [duplicate]

Tags:

c++

c++20

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);
like image 346
Kamath Avatar asked Sep 13 '21 17:09

Kamath


Video Answer


1 Answers

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

like image 95
Kamath Avatar answered Oct 22 '22 20:10

Kamath