Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare data members that are objects of any type in a class

Tags:

c++

templates

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:

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

compilation terminated due to -Wfatal-errors.

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

like image 349
dpham Avatar asked Jun 07 '11 06:06

dpham


People also ask

How do you declare data members in class?

You can declare a data member the same way as a variable, except that explicit initializers are not allowed inside the class definition. However, a const static data member of integral or enumeration type may have an explicit initializer.

Can we declare an object of another class as the data member?

As we know that a class contains data members and member function, and an object can also be a data member for another class.

Which data member is shared by all the objects of the class?

Static data members are class members that are declared using static keywords. A static member has certain special characteristics. These are: Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.


3 Answers

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;
};
like image 149
Xeo Avatar answered Oct 20 '22 08:10

Xeo


Member variables aren't allowed to be templates. Only member functions can be templates. You'll have to templatize the enclosing class B instead:

template <class T>
class B {
  std::list<A<T>*> objects;
};
like image 40
Rob Kennedy Avatar answered Oct 20 '22 07:10

Rob Kennedy


Unfortunately you cannot have template variables. Only option to declare a member data is to make the class template:

template<class T>
class B {
    std::list<A<T>*> objects;
};
like image 3
iammilind Avatar answered Oct 20 '22 08:10

iammilind