给定一个类中的数据成员 _value,定义如下:
unique_ptr<std::string> _value = nullptr;
以下内容无法编译。
auto getValue() const -> const decltype(*_value) &
编译器返回此错误:
“const”限定符不能应用于“std::basic_string&”
但是,如果我像这样声明函数:
auto getValue() const -> const remove_reference<decltype(*_value)>::type &;
它编译并按照我想要的方式运行(即本质上返回一个 const string&)
我觉得这很奇怪。这可能是 gcc 编译器中的错误,还是两个声明之间存在一些根本区别?
decltype(*_value) 正确地计算为 basic_string& ,这是 find 所以我想我可以在它前面添加一个 const ,它应该可以找到,但似乎会让编译器感到困惑......
请注意,我的意图基本上是让函数返回对 unique_ptr 指向的类型的 const 引用。
最佳答案
看起来这个问题已在 gcc 5.0
中修复,我们可以使用 wandbox 在线测试。但作为 T.C.注意,C++11 标准草案 8.3.2
中的 const 在应用于引用时会被忽略:
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name (7.1.3, 14.1) or decltype-specifier (7.1.6.2), in which case the cv-qualifiers are ignored.
关于c++ - 字符串的 decltype 和 const 引用返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29109500/