0

I made this program where you have some kind of Data, which type is choosen by the user. User save his work, and in the xml save file i want to write what type of variable he used, so when i have to open saves my program allocates the right template of Data example:

C++:

template <class T>
class Data{
private:
T variable;
...
};

XML:

<header>
  <type>int</type>
</header>

so here when i load the save file I want to have a Data<int> allocated...

user1709665
  • 142
  • 7

1 Answers1

1

You need to create factories, and a manager that 'maps' the value name (in string form) to one of the factories. Like this:

class AbstractData {}

template <class T>
class Data : public AbstractData {
private:
    T variable;
    ...
};

class FactoryManager
{
    ...
    typedef std::function< AbstractData* () > Factory;   

    void registerFactory( const QString& name, const Factory& factory )
    {
        //  Check to see one is not already registered before adding.
        map_.insert( name, factory );
    }

    AbstractData* createData( const QString& name )
    {
        //  Check factory exists first.
        return map_[name]->createData();
    }

private:
    QHash< QString, Factory > map_;
}

...
FactoryManager manager;
manager.registerFactory( "int", [](){ return new Data< int >; } );
...
Data< int >* data = manager.createData( "int" );
cmannett85
  • 21,725
  • 8
  • 76
  • 119