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

标签 c++ c++11 decltype

考虑 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/

相关文章:

c++ - 如何在 C++ 中使用 UTF-8,从其他编码转换为 UTF-8

C++第二次动态分配,而第一次工作(相同大小)

c++ - 聚合初始化在 C++11 中何时有效?

C++ - 使用 AMD 源库的链接错误

c++ - Qt 工作线程——我必须为每个特定任务继承还是可以使用回调?

c++ - 抽象基类c++的析构函数和无构造函数

c++ - 无法编译代码,因为它在 C++11 中已弃用

c++ - decltype(constexpr 变量)

c++ - sfinae 关于在类主体外部定义的成员函数

c++ - 如果从 lambda 内部调用,无法实例化使用 decltype 推断返回类型的函数模板?