Empirically determine value category of C++11 expression?

后端 未结 2 919
夕颜
夕颜 2020-11-29 03:51

Each expression in C++11 has a value category. One of lvalue, xvalue or prvalue.

Is there a way to write a macro that, given any expression as an argument, will pro

相关标签:
2条回答
  • 2020-11-29 04:28

    decltype can return the declared type of an entity (hence the name), but can also be used to query the type of an expression. However, in the latter case the resulting type is 'adjusted' according to the value category of that expression: an lvalue expression results in an lvalue reference type, an xvalue in an rvalue reference type, and a prvalue in just the type. We can use this to our benefit:

    template<typename T>
    struct value_category {
        // Or can be an integral or enum value
        static constexpr auto value = "prvalue";
    };
    
    template<typename T>
    struct value_category<T&> {
        static constexpr auto value = "lvalue";
    };
    
    template<typename T>
    struct value_category<T&&> {
        static constexpr auto value = "xvalue";
    };
    
    // Double parens for ensuring we inspect an expression,
    // not an entity
    #define VALUE_CATEGORY(expr) value_category<decltype((expr))>::value
    
    0 讨论(0)
  • 2020-11-29 04:38

    You could also try using the clang API's Classification function to return the category of the expression from a clang AST containing the expression. This is, of course, far more complex than @Luc's solution, since it requires generating the actual AST through clang.

    0 讨论(0)
提交回复
热议问题