c++ - decltype(fun()) 用于 consteval 方法
问题描述
考虑以下代码。我可以用 GCC 10.2.0 和 Clang 11.0.0 编译它(如预期的那样):
#include <iostream>
template<int>
struct T {
static constexpr auto fun() noexcept { return 0; }
using type = std::remove_cvref_t<decltype(fun())>;
};
int main() {
decltype(T<1>::fun()) a = 1;
std::cout << a;
}
如果我替换constexpr
为consteval
,那么 Clang 会抱怨std::remove_cvref_t<decltype(fun())>
:
错误:不能在立即调用之外获取 consteval 函数 'fun' 的地址
GCC 编译它就好了。为什么?
解决方案
正如在问题评论中已经说过的那样,这是 CLang 错误。
仅当函数是静态方法时才会出现此错误,如果它是全局函数,则代码有效(请参阅此处的在线工作示例)。
因此解决这个问题的一种方法是使用全局函数来转发静态方法的结果。我在下面做了一个更高级的这种全局转发的例子。
#include <iostream>
#include <type_traits>
template <typename T, typename ... Args>
static consteval auto forward_fun(Args ... args) {
return T::fun(args...);
}
template <int I>
struct T {
static consteval auto fun(int i, bool f) noexcept {
return i + 1;
}
using type = std::remove_cvref_t<decltype(forward_fun<T>(123, true))>;
};
int main() {
T<1>::type a = 1;
std::cout << a;
return 0;
}
推荐阅读
- node.js - 使用 azure ad nodeJS SAML 实现 SSO
- angular - Angular BehaviorSubject 已延迟更新到前端
- osmnx - 如何在 OSMNX 中为路线的各个边缘指定颜色?
- sql - SQL 到具有当前表的 UNION 历史表(日期范围对齐)
- angular - 返回 oauth 客户端和 IdentityServer4 的 url 编码问题
- excel - 在最后一个单元格下方而不是上方插入一行
- firebase - Firebase Firestore 是否计算对同一文档的读取?
- c++ - 这个匿名构造函数调用有什么问题?
- java - AEM从吊索模型中的Valuemapvalue文件路径获取父节点
- .net - 重定向到 url 时,我仅在 chrome 中获得无效的 Xframe 选项