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++ - 我可以在 Qt 内部设置断点吗?

C++ 队列 - 简单示例

c++11 - 当 shared_ptr 中的引用数量减少时运行函数

c++ - 将参数传递给通用 lambda 时复制构造函数不正确

c++ - 自动模板参数可以传什么有限制吗?

c++ - 类需要什么才能允许自动关键字实例化?

c++ - 帮助在 C++ 中使用 PCRE

c++ - UDP 接收不工作

c - 将 C++ lambda 传递给旧的 C 函数指针

c++ - boost::shared_ptr 直接替换