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

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

    I solved the above question using two overloaded template functions. The first takes as input a reference to a lvalue and return true. Whereas the second function uses a reference to rvalue. Then I let the compiler match the correct function depending on the expression passed as input.

    Code:

    #include 
    
    template 
    constexpr bool is_lvalue(T&) {
        return true;
    }
    
    template 
    constexpr bool is_lvalue(T&&) {
        return false;
    }
    
    int main()
    {
        std::string a = std::string("Hello");
        std::cout << "Is lValue ? " << '\n';
        std::cout << "std::string() : " << is_lvalue(std::string()) << '\n';
        std::cout << "a : " << is_lvalue(a) << '\n';
        std::cout << "a+b : " << is_lvalue(a+ std::string(" world!!! ")) << '\n';
    } 
    

    Output:

    Is Lvalue ? 
    std::string() : 0
    a : 1
    a+b : 0
    

提交回复
热议问题