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?
发布于 2013-05-20 02:33:12
decltype可以返回实体的声明类型(因此而得名),但也可用于查询表达式的类型。然而,在后一种情况下,结果类型会根据表达式的值类别进行“调整”:左值表达式会产生左值引用类型,右值引用类型会产生x值,而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发布于 2013-05-20 04:13:18
您还可以尝试使用clang API的Classification函数从包含表达式的clang AST返回表达式的类别。当然,这比@Luc的解决方案复杂得多,因为它需要通过clang生成实际的AST。
发布于 2022-02-12 14:33:34
#ifndef _TPF_TYPE_NAME_H
#define _TPF_TYPE_NAME_H
template <typename T>
constexpr bool is_lvalue_helper = std::is_lvalue_reference<T>::value;
template <typename T>
constexpr bool is_xvalue_helper = std::is_rvalue_reference<T>::value;
template <typename T>
constexpr bool is_prvalue_helper = !(is_lvalue_helper<T> || is_xvalue_helper<T>);
template <typename T>
constexpr bool is_rvalue_helper = is_xvalue_helper<T> || is_prvalue_helper<T>;
template <typename T>
constexpr bool is_glvalue_helper = is_xvalue_helper<T> || is_lvalue_helper<T>;
#define is_lvalue(type_instance) is_lvalue_helper<decltype((type_instance))>
#define is_xvalue(type_instance) is_xvalue_helper<decltype((type_instance))>
#define is_prvalue(type_instance)is_prvalue_helper<decltype((type_instance))>
#define is_rvalue(type_instance) is_rvalue_helper<decltype((type_instance))>
#define is_glvalue(type_instance)is_glvalue_helper<decltype((type_instance))>
#endif // end of _TPF_TYPE_NAME_Hhttps://stackoverflow.com/questions/16637945
复制相似问题