Jaden
Jaden

Reputation: 65

Can you have a vector of templated objects with different template types?

I am wondering if there is a way to have a vector of templated objects with different template types example

    template<class T>
    class object
    {
    public:
        void function()
        {

        }
    };

    int main()
    {
        std::vector<object> v;
        v.push_back(object<int>());
        v.push_back(object<char>());
        v.push_back(object<const char*>());
    }


I get the following error "argument list for class template "object" is missing". I understand that I need to pass a type for the template, but is it possible to hold a collection of objects with varying template types? any help would be appreciated.

Upvotes: 0

Views: 631

Answers (1)

 RichardFeynman
RichardFeynman

Reputation: 533

Others can correct me if I am wrong but I think you have 3 options.

  1. Use a Variant. You don't provide a lot of details but if you cannot live with a defined set of possible values this may be too limiting.
  2. Use inheritance/polymorphism. You could declare some virtual class and have all your stored object implement that class. Your example code will not work with that as int and char are not objects and would need a wrapper.
  3. Just go full C and store everything as a void*. This is probably a bad idea.

If you provide details of what you plan to store it would be easier to advise you.

Upvotes: 2

Related Questions