Giuseppe Pes Giuseppe Pes - 1 year ago 73
C++ Question

How to determine programmatically if an expression is rvalue or lvalue in C++?

What's the best way to determine if an expression is a rvalue or lvalue in C++? Probably, this is not useful in practice but since I am learning rvalues and lvalues I thought it would be nice to have a function

which returns true if the expression passed in input is a lvalue and false otherwise.


std::string a("Hello");
is_lvalue(std::string()); // false
is_lvalue(a); // true

Answer Source

Most of the work is already done for you by the stdlib, you just need a function wrapper:

template <typename T>
constexpr bool is_lvalue(T&&) {
  return std::is_lvalue_reference<T>{};

in the case you pass a std::string lvalue then T will deduce to std::string& or const std::string&, for rvalues it will deduce to std::string

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download