模板继承和基础成员变量

4

我在尝试使用模板继承时遇到了奇怪的错误。

这是我的代码:

template <class T> class A {
public:
    int a {2};
    A(){};
};

template <class T> class B : public A<T> {
    public:
    B(): A<T>() {};
    void test(){    std::cout << "testing... " << a << std::endl;   };
};

这是错误信息:

error: use of undeclared identifier 'a'; did you mean 'std::uniform_int_distribution<long>::a'?
    void test(){    std::cout << "testing... " << a << std::endl;   }

如果这会影响到我使用的某些内容,我会使用以下标志:

-Wall -g -std=c++11

我真的不知道问题出在哪里,因为与没有模板的纯类相同的代码正常工作。


1
void test(){ std::cout << "testing... " << A<T>::a << std::endl; }; - Rerito
1个回答

8

我真的不知道哪里出了问题,因为与没有模板的纯类相同的代码可以正常运行。

这是因为基类(类模板A)不是非依赖基类,其类型不能确定而不知道模板参数。而a是一个非依赖名称。非依赖名称不会在依赖基类中查找。

要更正代码,您可以使名称a成为依赖名称,只有在实例化时才能查找依赖名称,此时必须探索确切的基础特化并将其知晓。

您可以

void test() { std::cout << "testing... " << this->a << std::endl; };

或者

void test() { std::cout << "testing... " << A<T>::a << std::endl; };

或者

void test() { 
    using A<T>::a;
    std::cout << "testing... " << a << std::endl; 
};

谢谢您的回答,现在我明白了 :) - Jiří Lechner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接