Koo*_*sha 6 c++ c++20 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;
}
Run Code Online (Sandbox Code Playgroud)
如果我替换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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
109 次 |
| 最近记录: |