为什么 std::result_of 不能与 lambda 一起使用?

2024-01-03

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

#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 都无法编译!

两者都认为“call”应该返回一个 lambda 函数! 他们不知道“call”返回一个int。

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


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

result_of http://en.cppreference.com/w/cpp/types/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();
}

现场演示 http://coliru.stacked-crooked.com/a/77743e573bc1e049


我认为如果你修复了你的原始代码应该可以编译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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 std::result_of 不能与 lambda 一起使用? 的相关文章

随机推荐