gpt4 book ai didi

c++ - 凭经验确定 C++11 表达式的值类别?

转载 作者:IT老高 更新时间:2023-10-28 12:56:20 25 4
gpt4 key购买 nike

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
}

VALUE_CAT如何实现?

最佳答案

decltype 可以返回实体的声明类型(因此得名),但也可以用于查询表达式的类型。但是,在后一种情况下,结果类型会根据该表达式的值类别进行“调整”:左值表达式导致左值引用类型,右值引用类型中的 xvalue,以及类型中的纯右值。我们可以利用这一点:

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++ - 凭经验确定 C++11 表达式的值类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16637945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com