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

前端 未结 4 774
甜味超标
甜味超标 2020-12-05 01:55

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 thoug

4条回答
  •  执念已碎
    2020-12-05 02:32

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

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

    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

    Note that Yakk's answer will return a different type, which allows for more flexibility and you should read that answer and probably use it instead.

提交回复
热议问题