简体   繁体   English

当使用模板支持functor作为参数时,我应该使用什么限定符?

[英]When using templates to support functor as arguments, what qualifier should I use?

Consider this code: 考虑以下代码:

template<class F>
void foo1(F f) { f(); }

template<class F>
void foo2(F const& f) { f(); }

template<class F>
void foo3(F&& f) { f(); }

Which version of foo should I use? 我应该使用哪个版本的foo foo1 is what I see most "in the wild" but I fear that it might introduce copies that I don't want. foo1是我在“野外”看到的最多,但我担心它可能会引入我不想要的副本。 I have a custom functor that is kind of heavy to copy so I would like to avoid that. 我有一个很复杂的自定义仿函数,所以我想避免这种情况。 Currently I'm leaning towards foo3 (as foo2 would disallow mutating functors) but I'm unsure about the implications. 目前我倾向于foo3 (因为foo2会禁止变异仿函数),但我不确定其含义。

I'm targeting C++11. 我的目标是C ++ 11。

I'd actually prefer foo3 over foo1 (though the body should be std::forward<F>(f)(); ) 我实际上更喜欢foo3不是foo1 (虽然正文应该是std::forward<F>(f)();

foo3 will cause type F to be deduced to the type that lets you perfectly forward the argument due to reference collapsing . foo3将导致类型F被推导为允许您因参考折叠而完美转发参数的类型。 This is useful, as you won't make copies of anything by default, and can maintain the value category (lvalue vs rvalue) if you decide you want to forward the functor to something that does want a copy of it. 这很有用,因为默认情况下你不会复制任何东西,并且如果你决定将仿函数转发给想要它的副本的东西,它可以保持值类别(左值与右值)。

In general, the first form ( foo1 ) is fine if your function is going to store its own copy of the functor, but the third form ( foo3 ) is better for forwarding (using) arguments. 一般来说,如果你的函数要存储它自己的仿函数副本,第一种形式( foo1 )就可以了,但第三种形式( foo3 )更适合转发(使用)参数。

I also recommend Scott Meyers' excellent post about universal references , as well as this related Stack Overflow question . 我还推荐Scott Meyers关于通用引用的优秀帖子,以及相关的Stack Overflow问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM