【问题标题】:C++ and the const reference to temporary binding issue (Implementing the D language pass by value and by reference rules in C++0X)C++ 和对临时绑定问题的 const 引用(在 C++0X 中实现 D 语言按值传递和按引用规则)
【发布时间】:2026-02-04 22:45:01
【问题描述】:

我想知道在 C++ 中模仿 D 语言规则以按值传递和按引用传递规则的可能性有多大。有关背景,请参阅以下两个参考资料(主要是 Alexandrescu):

http://bartoszmilewski.wordpress.com/category/d-programming-language/page/2/

http://groups.google.com/group/comp.std.c++/msg/303e3bf2407a7609?

其中一个关键区别在于 D 中的 const 引用不会(作为非 const 引用)绑定到临时对象。

但是,我不知道有什么方法可以定义泛型类 X,从而导致以下代码无法编译:

void f(const X& x) {...}
f( X() ); //Cannot disable binding of const ref to X

一种可能性是制作 fa 模板函数,检查传递的参数的右值/左值性(可能在 C++0X 中)并使用 disable_if 但这会使代码过于混乱并且不能很好地扩展。

另一种可能是引入模板类,如

template<class T> Ref<T> : public T {...} //D-style ref, does not bind to temporaries!

然后使用

void f(Ref<const X> x) {...} //Does not look bad....
f( X() ); //Compile error here is doable, I checked a similar example already...

但是,这样我就失去了编写带有 Ref 的模板函数的能力,因为以下将无法编译...

template<class T> void ft(Ref<const T> x) {...}
ft( X() ); //Template deduction error

你的想法是什么?任何建议/评论/帮助表示赞赏!

【问题讨论】:

  • 我的想法:如果你喜欢 D 那就用它吧!
  • 我可能会,但出于实际考虑,目前这不是一个选择:)
  • 有趣的问题。我也非常希望能够禁用此行为。当返回对那些“绑定”临时对象的引用时,它会产生许多错误,其中一些除了整个程序分析之外无法检测到......

标签: c++ templates c++11 metaprogramming


【解决方案1】:

右值引用重载:

void f(X&&); // undefined
void f(const X& x) {...}
f( X() ); // error: f(X&&) undefined

【讨论】:

  • 感谢您的有趣建议!我本来希望保留一个声明,因为很容易忘记额外的重载......
  • 另外,我认为这不适用于函数模板,因为重载说 T& 和 T&& 会导致歧义......
  • 除了链接器错误之外,您还可以尝试void f(X&amp;&amp;) = delete; 来获取编译时错误。
  • @UncleBens:说得好,C++0x 还是太新鲜了,不能用。
  • 这不适用于常量右值。你需要一个const X&amp;&amp;