模板函数是通过值还是通过右值引用获取lambda参数? [英] Should templated functions take lambda arguments by value or by rvalue reference?

查看:165
本文介绍了模板函数是通过值还是通过右值引用获取lambda参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC 4.7在C ++ 11模式下让我用两种不同的方式定义一个函数:

  //按值
template< class FunctorT>
void foo(FunctorT f){/ * stuff * /}

p>

  //通过r值引用
template< class FunctorT>
void foo(FunctorT&& f){/ * stuff * /}

不是:

  //通过引用
template< class FunctorT&
void foo(FunctorT& f){/ * stuff * /}

我可以取消模板的函数,只是采取std ::函数,而 foo 是小和内联,我想给编译器的最好的机会,内联的调用f它使内部。前两个,如果我特别知道我通过lambdas,为什么不允许传递lambdas到最后一个,更好的性能?

解决方案

FunctorT&&& 是一个通用引用,可以匹配任何东西,不仅仅是右值。这是在C ++ 11模板中传递东西的首选方法,除非你绝对需要副本,因为它允许你使用完美的转发。通过 std :: forward< FunctorT>(f)访问该值,这将使 f 是以前,否则会把它作为一个左值。了解更多有关转发问题的此处,以及 std :: forward 和请阅读此处,了解如何 std :: forward 真的有效。 也是一个有趣的阅读。



FunctorT& 只是一个简单的左值引用,不能将临时表达式(lambda表达式的结果)绑定到。

GCC 4.7 in C++11 mode is letting me define a function taking a lambda two different ways:

// by value
template<class FunctorT>
void foo(FunctorT f) { /* stuff */ }

And:

// by r-value reference
template<class FunctorT>
void foo(FunctorT&& f) { /* stuff */ }

But not:

// by reference
template<class FunctorT>
void foo(FunctorT& f) { /* stuff */ }

I know that I can un-template the functions and just take std::functions instead, but foo is small and inline and I'd like to give the compiler the best opportunity to inline the calls to f it makes inside. Out of the first two, which is preferable for performance if I specifically know I'm passing lambdas, and why isn't it allowed to pass lambdas to the last one?

解决方案

FunctorT&& is a universal reference and can match anything, not only rvalues. It's the preferred way to pass things in C++11 templates, unless you absolutely need copies, since it allows you to employ perfect forwarding. Access the value through std::forward<FunctorT>(f), which will make f an rvalue again if it was before, or else will leave it as an lvalue. Read more here about the forwarding problem and std::forward and read here for a step-by-step guide on how std::forward really works. This is also an interesting read.

FunctorT& is just a simple lvalue reference, and you can't bind temporaries (the result of a lambda expression) to that.

这篇关于模板函数是通过值还是通过右值引用获取lambda参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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