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

前端 未结 4 770
甜味超标
甜味超标 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:13

    I would take a page from boost::hana and make the return value of is_lvalue encode the lvalue-ness of its argument both as a constexpr value, and as a type.

    This lets you do stuff like tag dispatching without extra boilerplate.

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

    the body of this function does nothing, and the parameter's value is ignored. This lets it be constexpr even on non-constexpr values.

    An advantage of this technique can be seen here:

    void tag_dispatch( std::true_type ) {
      std::cout << "true_type!\n";
    }
    void tag_dispatch( std::false_type ) {
      std::cout << "not true, not true, shame on you\n";
    }
    
    tag_dispatch( is_lvalue( 3 ) );
    

    Not only is the return value of is_lvalue available in a constexpr context (as true_type and false_type have a constexpr operator bool), but we can easily pick an overload based on its state.

    Another advantage is that it makes it hard for the compiler to not inline the result. With a constexpr value, the compiler can 'easily' forget that it is a true constant; with a type, it has to be first converted to bool for the possibility of it being forgotten to happen.

提交回复
热议问题