模板继承和基本成员变量
Template inheritance and a base member variable
我在尝试使用模板继承时遇到一个奇怪的错误。
这是我的代码:
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
我真的不知道哪里出了问题,因为没有模板的纯 类 代码也能正常工作。
I really don't know what is wrong since the same code as pure classes without templating works fine.
这是因为基class(class模板A
)不是非依赖基class,不知道模板就不能确定它的类型争论。 a
是一个独立的名字。不在依赖库中查找非依赖名称 classes.
要更正代码,您可以使名称 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;
};
我在尝试使用模板继承时遇到一个奇怪的错误。 这是我的代码:
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
我真的不知道哪里出了问题,因为没有模板的纯 类 代码也能正常工作。
I really don't know what is wrong since the same code as pure classes without templating works fine.
这是因为基class(class模板A
)不是非依赖基class,不知道模板就不能确定它的类型争论。 a
是一个独立的名字。不在依赖库中查找非依赖名称 classes.
要更正代码,您可以使名称 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;
};