模板继承和基本成员变量 [英] Template inheritance and a base member variable
问题描述
尝试使用模板继承时出现了一个奇怪的错误。
这是我的代码:
template< class T> A级{
public:
int a {2};
A(){};
};
模板< class T> B类:公共A< T> {
public:
B():A< T>(){};
void test(){std :: cout<< 测试...<< a<<的std :: ENDL; };
};
这就是错误:
错误:使用未声明的标识符'a';你的意思是'std :: uniform_int_distribution< long> :: a'?
void test(){std :: cout<< 测试...<< a<<的std :: ENDL; }
如果它可能影响我使用这些标志的东西:
-Wall -g -std = c ++ 11
我真的不知道出了什么问题,因为与没有模板的纯类相同的代码工作正常。
< blockquote>
我真的不知道出了什么问题,因为与没有模板化的纯类相同的代码工作正常。
这是因为基类(类模板 A
)不是非依赖的基类,在不知道模板参数的情况下无法确定其类型。 a
是一个非独立的名称。非依赖名称不会在依赖基类中查找。
要更正代码,您可以将名称设为 a
依赖,依赖名称只能在实例化时查找,那时必须探索确切的基本专业化并且是已知的。
你可以
void test(){std :: cout<< 测试...<< this-> a<<的std :: ENDL; };
或
void test(){std :: cout<< 测试...<< A< T> :: a<<的std :: ENDL; };
或
void test(){
使用A< T> :: a;
std :: cout<< 测试...<< a<<的std :: ENDL;
};
I get a weird error when trying to use template inheritance. This is my code:
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; };
};
And this is the error:
error: use of undeclared identifier 'a'; did you mean 'std::uniform_int_distribution<long>::a'?
void test(){ std::cout << "testing... " << a << std::endl; }
And in case it could affect something I use these flags:
-Wall -g -std=c++11
I really don't know what is wrong since the same code as pure classes without templating works fine.
I really don't know what is wrong since the same code as pure classes without templating works fine.
This is because the base class (class template A
) is not a nondependent base class, its type can't be determined without knowing the template arguments. And a
is a nondependent name. Nondependent names are not looked up in dependent base classes.
To correct the code, you could make the name a
dependent, dependent names can be looked up only at the time of instantiation, at that time the exact base specialization must be explored and will be known.
You could
void test() { std::cout << "testing... " << this->a << std::endl; };
or
void test() { std::cout << "testing... " << A<T>::a << std::endl; };
or
void test() {
using A<T>::a;
std::cout << "testing... " << a << std::endl;
};
这篇关于模板继承和基本成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!