首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >凭经验确定C++11表达式的值类?

凭经验确定C++11表达式的值类?
EN

Stack Overflow用户
提问于 2013-05-20 02:19:09
回答 3查看 1.3K关注 0票数 29

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

有没有一种方法可以编写一个宏,在给定任何表达式作为参数的情况下,它会相应地产生字符串"lvalue“、"xvalue”或"prvalue“?

例如:

代码语言:javascript
复制
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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-05-20 02:33:12

decltype可以返回实体的声明类型(因此而得名),但也可用于查询表达式的类型。然而,在后一种情况下,结果类型会根据表达式的值类别进行“调整”:左值表达式会产生左值引用类型,右值引用类型会产生x值,而prvalue只会在该类型中产生。我们可以利用这一点为我们带来好处:

代码语言:javascript
复制
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
票数 50
EN

Stack Overflow用户

发布于 2013-05-20 04:13:18

您还可以尝试使用clang API的Classification函数从包含表达式的clang AST返回表达式的类别。当然,这比@Luc的解决方案复杂得多,因为它需要通过clang生成实际的AST。

票数 1
EN

Stack Overflow用户

发布于 2022-02-12 14:33:34

代码语言:javascript
复制
#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_H
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16637945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档