C++ 箭头类型产生左值

标签 c++ decltype lvalue rvalue

根据 C++ Primer,C++ 箭头运算符产生一个左值。此外,产生左值的表达式的 decltype 将产生引用类型。那么为什么以下 decltype 不会导致引用类型。

struct MyStruct {
   string name
};
MyStruct s;
s.name = "aname";
MyStruct* p = &s;
decltype (p -> name) str = s.name; //type of str will be string and not &string although p -> name yields an lvalue

最佳答案

来自 cppreference

If the argument is an unparenthesized id-expression or an unparenthesized class member access, then decltype yields the type of the entity named by this expression. If there is no such entity, or if the argument names a set of overloaded functions, the program is ill-formed.

在您的示例中就是这种情况,因此它将返回成员的基础类型,即 std::string

如果需要,您可以添加括号,以便 decltype 产生引用:

//'str' is a std::string&
decltype((p->name)) str = s.name;

关于C++ 箭头类型产生左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37167398/

相关文章:

使用 eval 的 Javascript 函数赋值

c++ - 通用引用模板类型总是评估为左值

c++:函数左值或右值

c++ - MFC:如何在具有 LVS_EX_CHECKBOXES 样式的列表 ctrl 中结束复选框按钮

c++ - boost shared_ptr 析构函数中未处理的异常异常

c++ - 将显式指定的函数模板重载作为模板参数传递的正确语法是什么?

c++ - 使用 decltype 转换一个值,这可能吗?

c++ - 仅在编辑另一个类后才编译更改

c++ - 类成员函数的 decltype

C++ 模板 type_trait enable_if 类是映射