试图编译这个简单的类:
#include <vector>
struct M
{
// interface
auto begin() -> decltype(identities.begin())
{
return identities.begin();
}
// implementation
private:
std::vector<int> identities;
};导致错误:
$ g++-510 where.cpp -std=c++11
where.cpp:57:35: error: ‘struct M’ has no member named ‘identities’
auto begin() ->decltype(this->identities.begin())
^
where.cpp:57:35: error: ‘struct M’ has no member named ‘identities’
$ clang++ where.cpp -std=c++11 -Wall -pedantic -Wextra
where.cpp:57:35: error: no member named 'identities' in 'M'
auto begin() ->decltype(this->identities.begin())
~~~~ ^为什么decltype没有看到类成员?
发布于 2015-07-03 09:16:06
来自N3337 basic.lookup.unqual/7:
在成员函数体或嵌套类定义之外的X类定义中使用的名称应以下列方式之一声明:
因为尾部返回类型是函数声明的一部分,而不是定义,所以它无法向前看在类中声明了什么,所以您需要在函数声明的前面声明该成员。
发布于 2015-07-03 09:18:55
如果C++14可用,则可以省略尾部返回类型,从而避免引用外部函数体之外的成员,并使代码更加紧凑:
auto begin() {
return identities.begin();
}通常,对这种转发方法使用decltype(auto)更正确,因此返回类型可以作为引用,尽管在这种特殊情况下是相同的(感谢@Nawaz):
decltype(auto) begin() {
return identities.begin();
}发布于 2015-07-03 09:14:15
在函数之前移动成员的声明如下:
#include <vector>
struct M
{
// implementation
private:
std::vector<int> identities;
public:
// interface
auto begin() -> decltype(identities.begin())
{
return identities.begin();
}
};https://stackoverflow.com/questions/31202899
复制相似问题