根据经验确定C++ 11表达式的值类别?

And*_*zos 25 c++ c++11

C++ 11中的每个表达式都有一个值类别.lvalue,xvalue或prvalue之一.

有没有办法编写一个宏,给定任何表达式作为参数,将产生一个字符串"lvalue","xvalue"或"prvalue"酌情?

例如:

int main()
{
    int x;

    cout << VALUE_CAT(x) << endl; // prints lvalue
    cout << VALUE_CAT(move(x)) << endl; // prints xvalue
    cout << VALUE_CAT(42) << endl; // prints prvalue
}
Run Code Online (Sandbox Code Playgroud)

怎么可以VALUE_CAT实现?

Luc*_*ton 43

decltype可以返回实体的声明类型(因此名称),但也可以用于查询表达式的类型.但是,在后一种情况下,根据该表达式的值类别对结果类型进行"调整":左值表达式导致左值引用类型,右值引用类型中的xvalue和仅类型中的prvalue.我们可以将此用于我们的利益:

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
Run Code Online (Sandbox Code Playgroud)

  • 我没有意识到`decltype`"映射"表达式值类别(lvalue,xvalue,prvalue)到引用类型(左值引用T,右值引用T,T).谢谢. (2认同)