经验决定C ++ 11表达式的值类别? [英] Empirically determine value category of C++11 expression?

查看:137
本文介绍了经验决定C ++ 11表达式的值类别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11中的每个表达式都有一个值类别。

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

有一种方法来写一个宏,给定任何表达式作为参数,将产生一个字符串lvalue,xvalue 或prvalue?

Is there a way to write a macro that, given any expression as an argument, will produce a string "lvalue", "xvalue" or "prvalue" as appropriate?

例如:

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
}

如何 VALUE_CAT 可实现?

推荐答案

类型的实体(因此名称),但也可以用于查询表达式的类型。但是,在后一种情况下,根据该表达式的值类别对结果类型进行调整:左值表达式导致一个左值引用类型,右值引用类型中的x值,以及类型中的prvalue。我们可以使用它来实现我们的利益:

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

这篇关于经验决定C ++ 11表达式的值类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆