c++ - 使用未声明的标识符与模板和继承后续

标签 c++ macos gcc compilation visual-studio-2012

我在这里遇到了与上一个问题相同的问题: Use of undeclared identifier in C++ with templates and inheritance

总而言之,我们尝试从子类访问模板类的 protected 属性。所描述的执行此操作的方法是使用 this->attribute 而不是仅使用 attribute。 问题是,我想知道为什么 visual studio 2012 不需要在变量引用前添加 this-> 来使程序正确编译和执行。我还想知道是否有办法在 gcc 或 OS X 上的其他编译器中拥有该功能。

编辑: 这是我用来在 visual studio 2012 中对此进行测试的代码。

//file a.h

template<class T>
class a
{
public:
    a(){value = 2;};
protected:
    T value;
};

template<class T>
class b: public a<T>
{
public:
    T getValue(){return value;};
};

//file main.cpp
#include <iostream>
#include "a.h"
using namespace std;
int main()
{
    b<int> myTest;
    cout<<myTest.getValue();
    system("pause");
    return 0;
}

这不是使用 g++ 编译的,而是使用 visual studio 2012 编译的。

最佳答案

我相信描述适用于这种情况的参数依赖查找规则的标准部分是 §14.6.2/3,其中规定如下:

In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

由于您的基类依赖于模板参数,因此不应检查依赖的基类作用域。然而,一些编译器犯了这个错误。例如,GCC 正在执行额外的依赖基类范围查找,即 fixed only in version 4.7 (缺陷号 2416329131)。我不知道为什么 Visual Studio 编译器允许它。但如果这样做,那么在这方面显然不符合标准。您不应该依赖那个错误,绝对不应该寻找具有类似错误的编译器来依赖。

关于c++ - 使用未声明的标识符与模板和继承后续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14534316/

相关文章:

python - 在 VS2013 中构建/包含 Boost.Python

perl - 如何在 OS X 中编辑文件元数据?

c - Portaudio:打开文件而不是使用麦克风

c - 如何避免有关类型的 printf 警告

c - 这段代码在 GCC 中意味着什么?

c++ - 如何捕获 C++/Windows 中的每个异常?

c++ - 代码具有特定于功能的变量,这些变量在范围之外更改值

c++ - 是否允许在同一个 Sqlite 数据库连接中启动多个事务?

eclipse - 在Mac Lion上运行Eclipse Juno 64位的问题

c - GCC:我怎样才能使这个编译和链接工作?