C++03 中的右值
在 C++03 中如何判断给定参数是否为右值?我正在编写一些非常通用的代码,如果可能的话需要引用,否则需要构造一个新对象。我可以重载以按值和按引用并让右值返回调用按值函数吗?
或者我是否有一种非常恶心的感觉,这就是为什么右值引用出现在 C++0x 中?
编辑:
is_rvalue = !(is_reference || is_pointer) ?
How can you tell whether or not a given parameter is an rvalue in C++03? I'm writing some very generic code and am in need of taking a reference if possible, or constructing a new object otherwise. Can I overload to take by-value as well as by-reference and have the rvalue returns call the by-value function?
Or do I have a very sickening feeling that this is why rvalue references are in C++0x?
Edit:
is_rvalue = !(is_reference || is_pointer) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
显然有一种方法可以确定 C++03 中的表达式是右值还是左值(我说显然是因为我不确定我对这项技术的理解程度)。请注意,为了使该技术可用,几乎需要预处理器宏。 Eric Niebler 写了一篇很好的文章,介绍了它的工作原理以及如何在 BOOST_FOREACH 中使用它:
请注意,这篇文章的阅读量相当大(至少对我来说);正如内布尔勒在其中所说:
使用本文中描述的右值检测可能会帮助您至少处理 C++0x 的右值引用解决的一些问题。
There apparently is a way to determine whether an expression is an rvalue or lvalue in C++03 (I say apparently because I'm not sure how well I understand the technique). Note that to make the technique usable, preprocessor macros are pretty much required. Eric Niebler has written a nice article about how it works and how it gets used in BOOST_FOREACH:
Note that the article is pretty heavy reading (at least it is for me); as Neibler says in it:
Using the rvalue detection described in the artcile might help you deal with at least some of the issues that C++0x's rvalue references solve.
你不能。你所能做的就是相信你的客户并欺骗:
那么恐怕 C++03 无法满足您的需求。
You can't. All you can do is trust your clients and cheat:
Then I'm afraid C++03 won't cut it for you.
你是对的,你需要 C++0x 和右值引用来做到这一点。
我能想到的最接近的事情是通过常量引用获取某些内容,因为它可以绑定到左值或右值(如果右值需要构造一个临时值,它会这样做)。也就是说,您的代码将无法区分两者。
You are correct, you need C++0x and rvalue references to do that.
The closest thing I can think of is to take something by const-reference as that can bind to either an lvalue or an rvalue (if the rvalue needs to construct a temporary it will). That said, your code will not be able to distinguish between the two.
是的。这正是它们被添加到 C++0x 中的原因。
您无法在 C++ 中创建重载来区分右值和左值。
Yup. That is exactly why they're added to C++0x.
You can't create overloads in C++ to distinguish between rvalues and lvalues.
我正在编写一些非常通用的代码,并且需要在可能的情况下获取引用,否则需要构造一个新对象。
这不是您想要的吗?
注意...
I'm writing some very generic code and am in need of taking a reference if possible, or constructing a new object otherwise.
Won't this do what you want?
Note that...