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);
As pointed out by, @cigien this is indeed a clang bug. It works fine with gcc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With