完美转发原始类型 [英] Perfect forwarding of primitive types

查看:77
本文介绍了完美转发原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为自己的数据结构实现一些类似于vector::emplace的方法.在一般情况下,我会实现它们,以便它们支持完美的转发,即使用rvalue-references,std::forward和类似的东西.

I need to implement some methods similar to vector::emplace for my own data structures. In the general case, I would implement them so that they support perfect forwarding, i.e., with rvalue-references, std::forward and that stuff.

但是,如果我知道要转发的所有参数都是原始类型,例如intfloat,该怎么办?为原始类型实现完美转发是否有意义?

However, what if I know that all parameters to forward are primitive types such as int or float. Does it make any sense to implement perfect forwarding for primitive types?

换句话说,假设我们仅使用基本类型作为模板参数,以下两个代码段之间是否有区别?

In other words, is there a difference between the following two code snippets, assuming that we only use primitive types as template parameters?

template <typename... Args>
void wrapper(Args&& ... args) {
   func(std::forward<Args>(args)...);
}

template <typename... Args>
void wrapper(Args ... args) {
   func(args...);
}

另外:如果我们知道模板参数只能是仅包含基本类型的类,有什么区别吗?还是仅包含基本类型的类以及其他仅包含基本类型的类?

Additionally: Is there any difference if we know that the template parameters can only be classes which contain only primitive types? Or classes that contains only primitive types and other classes which themselves contain only primitive types?

推荐答案

不,对基本类型使用完美转发绝对没有任何意义:

No, it absolutely does not make any sense to use perfect forwarding for basic types:

  1. 复制等同于移动它们.
  2. 与通过引用传递相比,复制它们的成本大约相同或更少(由于其他优化,尤其是指针混淆).
  3. 最好的代码是不存在的代码.

但是有一个例外:
无法避免通过引用获取输出参数.

There is one exception though:
There is no way to avoid taking output-parameters by reference.

此外,如果您仍在编写模板,则绝对确定您永远不会将其用于更复杂的类型吗?
YAGNI(您将不需要它)非常重要,但以后也不必通过不必要地限制您的界面来限制自己.

Also, if you are writing a template anyway, are you absolutely sure you will never want to use it with more complex types?
YAGNI (You ain't gonna need it) is very important, but not handicapping yourself later by unneccessarily restricting your interface is too.

永远记住一句古老的格言:过早的优化是万恶之源".

And always remember the old adage "Premature optimization is the root of all evil".

这篇关于完美转发原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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