Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast to reference type

Tags:

c++

Chapter 4.11.3 of the book C++ Primer says the following:

A named cast has the following form: cast-name<type>(expression); where type is the target type of the conversion, and expression is the value to be cast. If type is a reference, then the result is an lvalue.

Can anyone give an example of this? Is conversion to a reference even possible?

like image 380
L.S. Roth Avatar asked Sep 17 '25 05:09

L.S. Roth


1 Answers

Is conversion to a reference even possible?

Yes, depending on the object you begin with. Most simple example is one lvalue reference converted to another. This can even be an added cv-qualifier (or removed, with const_cast), such as:

int const & foo(int & i) {
    return static_cast<int const &>(i);
}

the derived-to-base casts and base-to-derived (dynamic) casts mentioned in the other answers are other such examples.

A more interesting example is the std::reference_wrapper, which is an object you can receive as an rvalue, and cast it to an lvalue reference of the contained type:

int & foo(std::reference_wrapper<int> i) {
    return static_cast<int &>(i);
}

Note that the cast above happens implicitly (I could've used return i), but in some contexts (e.g. capturing variables with auto type) you might want to write the cast explicitly.

What is meant in C++ Primer is simply that the behavior of casts in these examples, and others, is basically what you would expect - the result of a cast to a reference type is an lvalue.

like image 146
Benny K Avatar answered Sep 19 '25 20:09

Benny K