模板继承和基本成员变量

时间:2016-07-28 14:48:55

标签: c++ templates inheritance base-class

尝试使用模板继承时出现了一个奇怪的错误。 这是我的代码:

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 个答案:

答案 0 :(得分:8)

  

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

这是因为基类(类模板jdbc_driver_class => 'org.postgresql.Driver')不是非依赖基类,不能在不知道模板参数的情况下确定其类型。 A是一个非独立的名称。非依赖名称不会在依赖基类中查找。

要更正代码,您可以使名称a依赖,只能在实例化时查找相关名称,此时必须探索确切的基本特征并且将是已知的。

你可以

a

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

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