【问题标题】:Why is Visual Studio 2013 having trouble with this class member decltype?为什么 Visual Studio 2013 对此类成员 decltype 有问题?
【发布时间】:2014-07-03 21:30:57
【问题描述】:
#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

【问题讨论】:

  • 请参阅stackoverflow.com/a/11235245/103167,了解为什么这种编码风格在任何编译器中都被破坏了,您应该对this 的成员使用decltype 的尾随返回类型。

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


【解决方案1】:

这是 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 在 cmets 中指出的那样,read this answer 解释了为什么尾随返回类型应该是首选选项。


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

【讨论】:

  • 尾随返回类型怎么样,错误报告说它可以正常工作? auto begin() -&gt; decltype(v.begin()) { return v.begin(); } 对我来说似乎好多了,如果它工作正常
  • @BenVoigt 同意,更新了答案。感谢 litb 链接到那个答案,我不知道这个限制。
  • 链接失效了,但它是mentioned as being fixed in VS2015 here
  • @Timmmm 感谢您的链接,我已经更新了答案并删除了旧链接。 MS 决定关闭连接,并且像往常一样没有重定向,破坏了所有这些链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多