2016-07-28 76 views
3

尝试使用模板继承时出现奇怪的错误。 这是我的代码:模板继承和基本成员变量

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

'无效测试(){性病::法院<< “测试...” << A ::一<< std :: endl; };' – Rerito

回答

4

I really don't know what is wrong since the same code as pure classes without templating works fine.

这是因为基类(类模板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; 
}; 
+0

谢谢你的回答。它现在是有道理的:) –