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

Why does std::result_of not work with lambdas?

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

#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" returns 是一个整数。

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

那不是你叫std::result_of的方式,应该是:

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

或者你可以写得更简单:

auto call(const auto& f) -> decltype(f())
{
  return f();
}

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

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

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

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();
}

FUNCTION PARAMETER AS 'auto' 自 c++14 / c++1y
起受支持 <更简单的解决方案>
这里的问题是汽车将被视为相同类型 [由语言标准决定 - HATERS 会说 BUG]。

解决方案:

1) '->' 和 return 类型从 c++14 开始根本不需要,因为函数调用只有一个 return 语句。

2) 克服相同类型的所有汽车政策 [auto:1, auto:2,...], LETS GO VARIADIC

3) 明确检查是否有单个参数。

#include <initializer_list>

auto call(const auto&... f)
{
    static_assert(sizeof...(f)==1,"Exactly 1 argument should be provided");
    return std::begin({f...})[0]();   // black magic : to call first arg of singleton pack
}


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

希望它能解决您的问题。 注意:在 TDM GCC 4.9.2、cygwin gcc 5.0

中测试

应使用 -std=c++14 或 -std=c++1y

编译