【发布时间】: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