模板继承和基本成员变量 [英] Template inheritance and a base member variable

查看:252
本文介绍了模板继承和基本成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆