首页 > 解决方案 > 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; 
}

如果我替换constexprconsteval,那么 Clang 会抱怨std::remove_cvref_t<decltype(fun())>

错误:不能在立即调用之外获取 consteval 函数 'fun' 的地址

GCC 编译它就好了。为什么?

标签: c++c++20consteval

解决方案


正如在问题评论中已经说过的那样,这是 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;
}

推荐阅读