我有一个带有引用的类,并且想要一个返回指针的 getter。
class X {
std::string& text;
public:
auto GetText() -> decltype(text) * { return &text); // doesn't work
X(std::string& text): text(text) {}
};
简单的方法是传递一个指向这个类的指针。但是如果我传递一个引用,我能得到一个带有 getter 的指针吗?
编辑:这是错误消息
error: cannot declare pointer to 'std::__cxx11::string& {aka class std::__cxx11::basic_string<char>&}'
auto GetText() -> decltype(text) * { return &text);
^
首先,
auto GetText() -> decltype(text) * { return &text); // doesn't work
是声明此签名的一种非常可恶的方式。更喜欢
std::string* GetText(){ return &text);
甚至只是
auto GetText(){ return &text);
但这不是代码审查。
这里的问题是您要求指向text
成员变量的声明类型的指针,该类型是字符串引用 ( std::string&
)。从评论部分来看,您似乎没有意识到decltype
尊重其论点的“引用”、“常量”和“易变”。
在 C++ 中不能有指向引用的指针,例如std::string&*
格式错误。调用std::remove_reference_t应该可以解决这个问题,例如
auto GetText() -> std::remove_reference_t<decltype(text)> * { return &text);
但是,在这种情况下,auto
无论如何都会正确推断出您的类型,因此您的显式声明是不必要的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句