C ++ and a constant reference to the problem of temporary binding (the implementation of the D language passes by value and by reference rules in C ++ 0X)

I was wondering to what extent you can simulate D language rules for passing by value and passing by reference rules in C ++. For more information, see the following two links (mainly Alexandrescu):

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

and

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

One of the key differences is that links D const do not bind (as not const) to temporary ones.

However, I don’t know how to define a generic class X so that the following code cannot compile:

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

One possibility could be to create a fa template function, check the rvalue / lvalue-ness argument passed (possibly in C ++ 0X), and use disable_if, but this clutters the code too much and is not scaled enough.

Another possibility might be to introduce a template class, for example

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

and then use

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

However, in this way, I lose the ability to write template functions by accepting Ref, as the following will not compile ...

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

What are your thoughts? Any suggestion / comment / help is appreciated!

+4
source share
1 answer

Overload by rvalue link:

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

Source: https://habr.com/ru/post/1335162/


All Articles