decltype(data) {} // ERROR int data; };-6ren">
gpt4 book ai didi

c++ - 类方法声明中的 decltype : error when used before "referenced" member is declared

转载 作者:可可西里 更新时间:2023-11-01 16:38:16 26 4
gpt4 key购买 nike

考虑 following code :

struct test {    
auto func() -> decltype(data) {} // ERROR

int data;
};

int main() {
test t;
t.func();
}

它给出了以下错误:

main.cpp:2:29: error: 'data' was not declared in this scope
auto func() -> decltype(data) {}

但是,如果我将 data 放在 func() 之上,它不会给出任何错误 (live code):

struct test {    
int data;

auto func() -> decltype(data) {}
};

...

所以我的问题是,为什么 decltype 不考虑在它之后声明的成员(当 decltype 用于方法声明而不是定义时)?我还想知道在语言标准的 future 迭代中这种行为是否有任何变化。


请注意,我问这个是因为我期望 decltype 有不同的行为。我的编码约定是将类数据成员放在类函数下面。这种不同的行为肯定会影响我组织类(class)成员的方式。如果您能提供任何可以保留我的编码约定的解决方法,我将不胜感激。

最佳答案

尾随返回类型是成员函数声明的一部分,与成员函数定义不同,它不能访问数据成员或声明在它之后的成员函数,哪个呢。我不知道 C++14 中此行为有任何变化。

参见 C++11 标准的 3.4.1-7,非限定名称查找:

A name used in the definition of a class X outside of a member function body or nested class definition shall be declared in one of the following ways:

  • before its use in class X or be a member of a base class of X (10.2), or...

(强调我的)

关于c++ - 类方法声明中的 decltype : error when used before "referenced" member is declared,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16766137/

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