作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
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/
我是一名优秀的程序员,十分优秀!