gpt4 book ai didi

c++ - 为什么 std::result_of 不适用于 lambda?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:06:51 25 4
gpt4 key购买 nike

我设法将我的案例简化为以下最简单的代码:

#include <type_traits>

auto call(const auto& f) -> typename std::result_of<decltype(f)()>::type
{
return f();
}

int main()
{
return call([] { return 0; });
}

gcc-4.9.2 和 gcc-5.0.0 都不编译!

两者都认为“调用”应该返回一个 lambda 函数!不要弄清楚“调用”返回一个 int。

这是编译器中的错误还是我的 C++ 关闭了?非常感谢。

最佳答案

您的代码不是有效的 C++,因为函数参数类型不能是 auto,此语法已为 Concepts Lite 提出,并可能在未来成为该语言的一部分。

result_of需要一个调用表达式,它将从中推断出返回类型。

修复这两个问题,您的代码变为

template<typename F>
auto call(F const& f) -> typename std::result_of<decltype(f)()>::type
// or typename std::result_of<F()>::type
{
return f();
}

或者你可以直接使用

template<typename F>
auto call(F const& f) -> decltype(f())
{
return f();
}

Live demo


我认为如果您修复了 result_of 表达式,您的原始代码应该可以编译,但它不会在 gcc-4.9 或 5.0 上;也许这是 gcc 扩展的错误,它允许参数类型为 auto

// This fails to compile
auto call3(const auto& f) -> typename std::result_of<decltype(f)()>::type
{
return f();
}

关于c++ - 为什么 std::result_of 不适用于 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28618788/

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