gpt4 book ai didi

c++ - decltype(fun()) 用于 consteval 方法

转载 作者:行者123 更新时间:2023-12-03 06:50:19 24 4
gpt4 key购买 nike

考虑以下代码。我可以用 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())> :

error: cannot take address of consteval function 'fun' outside of an immediate invocation


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

最佳答案

正如在对问题的评论中已经说过的那样,这是 CLang 错误。
仅当函数是静态方法时才会出现此错误,如果它是全局函数,则代码有效(参见工作 online example here)。
因此,解决此问题的一种方法是使用全局函数来转发静态方法的结果。我在下面做了一个关于这种全局转发的更高级的例子。
Try it online!

#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;
}

关于c++ - decltype(fun()) 用于 consteval 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64762278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com