gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:37:07 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com