Create std::list of templated structs (C++)

804 views Asked by At

I have a struct defined as follows:

template <typename T> 
struct data {
  int num;
  T *ptr;
};

I want to create a std::list of various data structs using different types like:

struct data<My_Favorite_Type> a;
struct data<My_Second_Favorite_Type> b;

I'm just not sure if it's possible to declare a std::list that accepts both these structs. Is creating a std::list of these possible? As a workaround I think I could just make my struct into a generic linked list, but i'd really like to just use the std library if at all possible.

3

There are 3 answers

0
Tom Kerr On BEST ANSWER

The types stored inside of the std containers must be uniform. So you can't do this:

std::list<data> some_data;
some_data.push_back(data<int>());
some_data.push_back(data<float>());

Sometimes just having two lists is the right solution. :)

There are a few alternative ways to think about the problem, though its hard to say whether they are appropriate for you.

They can be pointers and handled dynamically. In this example it doesn't actually matter what the data is, we just want to print it.

struct base {
  virtual ~base() {}
  virtual void print() const = 0;
};

template<typename T>
  struct data : public base {
    virtual void print() const {std::cout << num << std::endl;}
    int num;
    T *ptr;
  };

std::list<base *> some_data;

You can also use boost::variant.

typedef boost::variant<
    data<int>
    ,data<float>
  > data_variant;

std::list<data_variant> some_data;

The other tool that makes variants pleasant is boost::static_visitor.

3
Michael Krelin - hacker On

The verbose answer is "no, it's not possible" (and non-verbose is too short for an answer).

0
Paul Eastlund On

No, what you're looking to do is not possible, but you can get there with a little extra work if you use something like boost::any.