如何声明作为类中任何类型的对象的数据成员 [英] How to declare data members that are objects of any type in a class

查看:128
本文介绍了如何声明作为类中任何类型的对象的数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这篇文章中,我试图在B类中声明一个列表,它可以容纳任何类型的A类对象,例如A< int>,A< double>,A< float&我打算在运行时添加A对象到列表中:

In this piece I'm trying to declare in Class B a list that can hold objects of Class A of any type, such as A<int>, A<double>, A<float>. I intend to add A objects to the list during runtime:

#include <list>

template <class T> class A {};

class B {
    template<class T> std::list<A<T>*> objects;
};

看起来像这样的列表应该可以工作,但编译它会出现错误:

It seems like making a list like this should work but compiling it gives an error:


第6行:错误:data member'objects'不能是成员模板

Line 6: error: data member 'objects' cannot be a member template

由于-Wfatal错误。

compilation terminated due to -Wfatal-errors.

有人可以解释为什么这不工作,我怎么能解决它?

Can somebody explain why this doesn't work and how I can fix it?

推荐答案

这不是C ++的工作原理。如果要将不同的对象组合在一起,则它们至少需要具有某些关系。作为相同类模板的实例化并不意味着它们是相关的,它们是完全不同的类型。如果你想要一个 A< T> * 的列表,最好通过虚函数建立一个基类指针和转发操作的列表:

That's just not how C++ works. If you want to group different objects together, they need to have at least some relation. Being instantiations of the same class template doesn't imply that they are related, they're completely distinct types. If you want a list of A<T>*s, better make a list of base-class pointers and forward operations through virtual functions:

class A_base{
public:
  virtual void foo() = 0;
  virtual ~A_base() { }
};

template<class T>
class A : public A_base{
public:
  void foo(){
    // ...
  }
};

class B{
  std::list<A_base*> objects;
};

这篇关于如何声明作为类中任何类型的对象的数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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