c++ - 为什么 Visual Studio 2013 对此类成员 decltype 有问题?

标签 c++ visual-c++ c++11 visual-studio-2013 decltype

#include <vector>

struct C
{
    std::vector<int> v;
    decltype(v.begin()) begin() { return v.begin(); }
    decltype(v.end()) end() { return v.end(); }
};

Clang++没有问题,但是MSVC 2013报如下错误:

error C2228: left of '.begin' must have class/struct/union

最佳答案

这是 VS2013 中的一个已知错误,fixed 在 VS2015 中。如果您改用尾随返回类型,编译器将接受该代码。

struct C
{
    std::vector<int> v;
    auto begin() -> decltype(v.begin()) { return v.begin(); }
    auto end()   -> decltype(v.end())   { return v.end(); }
};

正如错误报告所说,另一种解决方法是使用:

struct C
{
    std::vector<int> v;
    decltype(std::declval<decltype(v)>().begin()) begin() { return v.begin(); }
    decltype(std::declval<decltype(v)>().end())   end()   { return v.end(); }
};

但正如@BenVoigt 在评论中指出的那样,read this answer为什么尾随返回类型应该是首选选项。


在链接页面中搜索类成员访问的 C++ decltype 未完全实现

关于c++ - 为什么 Visual Studio 2013 对此类成员 decltype 有问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24563593/

相关文章:

c++ - 为什么 `std::unordered_map` "speak like the Yoda"- 重新排列元素?

c++ - 初始化结构的私有(private)成员

c++ - 交换动态分配的数组错误

c++ - 您将如何为对象产生滚动效果?

c++ - 使用 WinCE7 平台构建器在 Visual Studio 2008 中为 WinCE7 在 Visual C++ 中创建 Winforms

c++ - 基于范围的循环 : Auto changes meaning in C++11

C++ 字符串成员构造

c++ - 是否有像 auto_ptr 和 shared_ptr 这样不需要 C++0x 的通用智能指针?

c++ - ntohl(*(uint32_t*) ...) 是做什么的?

c++ - 将缓冲区对齐到 N 字节边界而不是 2N 字节边界?