gpt4 book ai didi

C++ 箭头类型产生左值

转载 作者:可可西里 更新时间:2023-11-01 18:18:24 33 4
gpt4 key购买 nike

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

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com