c++ - 字符串的 decltype 和 const 引用返回类型

标签 c++ c++11 auto decltype

给定一个类中的数据成员 _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/

相关文章:

c++ - 当 memcpy() 比 memmove() 快时,什么是真正重要的情况?

c++ - 沮丧 : why: ‘A’ is an inaccessible base of ‘B’ ?

c++ - 如何防止在 for_each 的末尾调用复制构造函数?

c++ - 从 C++11 中的多个线程获取值,而无需等待任何给定线程完成执行

reactjs - 如何将分片bin文件合并为一个

c++ - 迭代器有什么意义?

c++ - 指针在字符串C++中的输出位置

c++ - 模板类中模板类的结构体

c++ - auto 和 decltype(auto) 类型推导示例

c++ - 通用 lambda 在 C++14 中如何工作?