为什么std :: result_of不能使用lambdas? [英] Why does std::result_of not work with lambdas?

查看:305
本文介绍了为什么std :: result_of不能使用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都没有编译! p>

两者都认为call应该返回一个lambda函数!
不要弄明白call返回一个int。



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

解决方案

您的代码无效C ++,因为函数参数类型不能为 auto ,此语法已被提议用于Concepts Lite,并且可能会成为未来语言的一部分。



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



修复这两个问题,你的代码变成

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

或者您可以使用

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

演示






我认为如果你修复了 result_of 表达式,但它不在gcc-4.9或5.0上;也许这是一个与gcc扩展的错误,允许参数类型 auto

  //这无法编译
auto call3(const auto& f) - > typename std :: result_of< decltype(f)()> :: type
{
return f();
}


I managed to reduce my case to the following simplest piece of code:

#include <type_traits>

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

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

Neither gcc-4.9.2 and gcc-5.0.0 compile!

Both think that "call" should be returning a lambda function! The don't figure out that "call" returns an int.

Is this a bug in the compiler or is my c++ off? Many thanks.

解决方案

Your code's not valid C++ because function parameter types cannot be auto, this syntax has been proposed for Concepts Lite and may become part of the language in the future.

result_of needs a call expression from which it will deduce the return type.

Fixing both of these, your code becomes

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

Or you could just use

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

Live demo


I think your original code should compile if you fix the result_of expression, but it doesn't on gcc-4.9 or 5.0; maybe this is a bug with the gcc extension that allows parameter types to be auto

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

这篇关于为什么std :: result_of不能使用lambdas?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆