0

I'm creating self-registering classes following this example:

I got the example up and running but now I find myself in the trouble of needing to pass arguments to constructor of the derived class in a fashion similar to this:

int* n = generateRandomInteger();
std::string attributes = readFirstLine(file);
// converts the string of attributes in a map of strings
std::map<string, string>* m = createMap(attributes);
// n and m would be parameters that the constructor would use
Base* b = BaseFactory::createInstance(object_components->Attribute("id"),n,m);

All derived classes would be taking the same amount or arguments with the same type, so I guess the function template used to create the new object could use these fixed types.

What I try is this:

#ifndef BFACT_H
#define BFACT_H

#include "B.h"
#include <iostream>

template<typename T>
B * createT(int* a, std::string* b)
{
  return new T(a,b);
}

struct BaseFactory {

    //typedef std::map<std::string, B*(*)(SDLGameObject*,std::map<string,string>*)> map_type;
    typedef std::map<std::string, B*(*)(int*,std::string*)> map_type;

    static B * createInstance(std::string const& s, int* a, std::string* b)  {
        map_type::iterator it = getMap()->find(s);
        if(it == getMap()->end())
            return 0;
        return it->second(a,b);
    }

protected:
    static map_type * getMap() {
        // never delete'ed. (exist until program termination)
        // because we can't guarantee correct destruction order 
        if(!map)
        {
          map = new map_type;
        } 
        return map; 
    }

private:
    static map_type * map;

};

template<typename T>
struct DerivedRegister : BaseFactory { 

    DerivedRegister(std::string const& s)
    { 
        getMap()->insert(std::make_pair(s, &createT<T>(int*, std::string*)));
    }
};

#endif // BFACT_H

but the number of errors I get is too damn high.

Community
  • 1
  • 1
roymcclure
  • 404
  • 3
  • 12
  • `BaseFactory::createInstance(object_components->Attribute("id"),n,m)` .. `m` is a pointer to a `std::map` while you defined `createInstance` to take the 3rd argument as a pointer to `std::string` ... is that one of the errors? – txtechhelp Jan 13 '16 at 19:52
  • Well, what are the errors? If there's way too many, then pick some to ask about. – user253751 Jan 13 '16 at 20:01

0 Answers0