Home > Software design >  c initialize vector with pointers to class template
c initialize vector with pointers to class template

Time:01-23

i try to init std vector with pointer to tamplate class
using c 11 and g
Like this and it fail:

template <typename T>
struct Column  
{
    Column( T data)
    {             
        this->data = data;
    }

    T data;
    
}; 

int main(int argv,char** argc)
{
  std::vector<std::vector<Column*>> csv;
  
}

This i need to i can init Column with diffrent types like this :

 Column<std::string>* tmpString = new Column<std::string>(each);
 csv[0].push_back(tmpString);    

or 

 Column<int>* tmpInt = new Column<int>(each);
 csv[0].push_back(tmpString); 

is there any way to do this ? or maybe better way ?

CodePudding user response:

It is not possible to do it directly, you will need an abstract baseclass/interface to do something like that.

Also don't use naked new/delete and prefer std::unique_ptr so your instances get cleaned up when vector goes out of scope.

Demo : https://onlinegdb.com/lIhmM_RC3z

Example :

#include <iostream>
#include <string>
#include <vector>
#include <memory>

struct ColumnItf
{
    virtual void visit() const = 0;
};

template<typename type_t>
class Column :
    public ColumnItf
{
public:

    explicit Column(const type_t& data) :
        m_data{ data }
    {
    }

    void visit() const override
    {
        std::cout << m_data << "\n";
    }

private:
    type_t m_data;
};

int main()
{
    std::vector<std::unique_ptr<ColumnItf>> columns;
    
    columns.emplace_back(std::make_unique<Column<int>>(1));
    columns.emplace_back(std::make_unique<Column<std::string>>("Hello"));
    
    for (const auto& itf : columns)
    {
        itf->visit();
    }

    return 0;
}
  • Related