根据 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/