C++ 箭头类型产生左值
C++ arrow type yields lvalue
根据 C++ Primer,C++ 箭头运算符产生一个左值。此外,产生左值的表达式的 decltype
将产生引用类型。那么为什么下面的 decltype not 导致引用类型。
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
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.
您的示例就是这种情况,因此它将 return 成员的基础类型,即 std::string
。
如果需要,您可以添加括号,以便 decltype
产生参考:
//'str' is a std::string&
decltype((p->name)) str = s.name;
来自 decltype
(来自 §7.1.6.2/4 [dcl.type.simple]):
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.
p->name
属于上述情况,所以decltype(p->name)
的类型是p->name
的类型,是std::string
而不是std::string&
。
另一方面,decltype((p->name))
是 std::string&
因为 (p->name)
是一个左值表达式。
根据 C++ Primer,C++ 箭头运算符产生一个左值。此外,产生左值的表达式的 decltype
将产生引用类型。那么为什么下面的 decltype not 导致引用类型。
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
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.
您的示例就是这种情况,因此它将 return 成员的基础类型,即 std::string
。
如果需要,您可以添加括号,以便 decltype
产生参考:
//'str' is a std::string&
decltype((p->name)) str = s.name;
来自 decltype
(来自 §7.1.6.2/4 [dcl.type.simple]):
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.
p->name
属于上述情况,所以decltype(p->name)
的类型是p->name
的类型,是std::string
而不是std::string&
。
另一方面,decltype((p->name))
是 std::string&
因为 (p->name)
是一个左值表达式。