consteval with templates possible?(有可能使用模板吗?)
本文介绍了有可能使用模板吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制作一些模板版本的consteval函数,我不清楚这里是否有任何限制。
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);
}
大多数情况下工作正常-
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
我再次看到依赖于Consteval函数的模板化版本的编译错误。具体地说,此用例无法编译
std::cout << mid(1,2,3) << std::endl; // templated version fails to compile
错误-
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);
推荐答案
正如@cigien所指出的,这确实是一个clang bug。它和GCC相处得很好。
这篇关于有可能使用模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:有可能使用模板吗?


猜你喜欢
- 将 hdc 内容复制到位图 2022-09-04
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- GDB 不显示函数名 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- XML Schema 到 C++ 类 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- DoEvents 等效于 C++? 2021-01-01