Search code examples
c++types

Convert a literal to an lvalue


In C, there is the concept of a compound literal which can be used to take any literal and make it addressable. For instance:

int* p = &(int){0};

Compound literals do not exist in C++. Is there another construct in C++ that can turn a literal into an lvalue? For example:

// Something semantically equivalent to this, but without the need of a declaration
int n = 0;
int* p = &n;

EDIT:

Having a function or type to create the solution is fine, as long as no more than a single inline statement is needed to facilitate its use. For example, int* p = new int(0); requires two lines per instance of use: one line where it is used, and one line at the end of scope to delete the allocation.

Solution must be doable in standard C++; no extensions.


Solution

  • You can define

    template<class T>
    T& lvalue_cast(T &&t) {return static_cast<T&>(t);}
    

    which accepts literals (among other things). The cast is needed as of C++23.

    The temporary lasts until the end of the complete expression lexically containing its creation (presumably materialization to bind the reference for lvalue_cast). Obviously restricting its use to that interval is up to you.