模板传递值或const引用或...? [英] template pass by value or const reference or...?

查看:97
本文介绍了模板传递值或const引用或...?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以这样写一个模板函数

I can write a templated function this way

template<class T> void f(T x) {...}

b

template<class T> void f(T const& x) {...}

我想第二个选项可以更好的,因为它明确地避免了副本,但我怀疑它也可以失败一些特定类型 T (例如函子?)。
那么,什么时候应该使用第一个选项,什么时候使用第二个呢?还有这些 boost :: call_traits< T> :: param_type boost :: reference_wrapper 到我的以前的问题,但是人们不会在任何地方使用它们,是吗?有什么经验法则吗?

I guess that the second option can be more optimal as it explicitly avoids a copy, but I suspect that it can also fail for some specific types T (eg functors?). So, when should use the first option, and when to use the second? There are also this boost::call_traits<T>::param_type and boost::reference_wrapper that were in the answers to my previous question, but people don't use them everywhere, do they? Is there a rule of thumb for this? Thanks.

推荐答案


有没有经验法则?

Is there a rule of thumb for this?

当使用传递引用与值传递的相同一般规则适用。

The same general rules for when to use pass by reference vs. pass by value apply.

你期望 T 始终是一个数字类型或一个非常便宜的类型,然后你可以通过值接受参数。如果你要将参数的副本复制到函数中的一个局部变量中,那么你应该把它的值改为

If you expect T always to be a numeric type or a type that is very cheap to copy, then you can take the argument by value. If you are going to make a copy of the argument into a local variable in the function anyway, then you should take it by value to help the compiler elide copies that don't really need to be made.

否则,接受参数的值。通过引用。在类型廉价复制的情况下,它可能更昂贵,但对于其他类型,它会更快。如果你发现这是一个性能热点,你可以重载不同类型的参数的函数,并为每个参数做正确的事情。

Otherwise, take the argument by reference. In the case of types that are cheap to copy, it may be more expensive but for other types it will be faster. If you find this is a performance hotspot, you can overload the function for different types of arguments and do the right thing for each of them.

这篇关于模板传递值或const引用或...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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