Objects not registered in the factory when the code is compiled as a library but works fine as stand alone

67 views Asked by At

We are trying to transform a code of ours into a library to allow some interfacing with other codes. In the code, we use a lot an object factory relying on the singleton pattern where objects are declared via macros, implemented as hereafter.

Our problem is that when we compile the whole code as a library, objects are not registered anymore in the factory and cannot be created at execution. Would you have any suggestion ? Notably, should something be made extern ? I must confess I reach my limits...

Thanks a lot !

Marc

template<typename AClass> class Factory
{
public :

    //! typedef for function creating object by the Factory
    typedef AClass*(*CreateFunc)();

    bool Register(const std::string& id,
          CreateFunc creator)
    {
        return _associations.insert(typename AssocMap::value_type(id, creator)).second;
    }

    bool Unregister(const std::string& id)
    { return _associations.erase(id) == 1; }

    AClass* CreateObject(const std::string& id)
    {

        typename AssocMap::const_iterator i=_associations.find(id);
        if(i!= _associations.end())
            return (i->second)();
        else
            {
                std::cerr << "Unknown Type in object factory : " << id << std::endl;
                exit(-1);
            }
    }

    AClass* CreateObjectIfAvailable(const std::string& id)
    {

        typename AssocMap::const_iterator i=_associations.find(id);
        return (i!= _associations.end() ? (i->second)() : NULL);

    }

    static Factory & Instance()
    {
        static Factory obj;
        return obj;
    }

private:

    //! AssocMap typedef used for map establishing correspondance between CL and std::strings
    typedef std::map<std::string,CreateFunc> AssocMap;

    // Singleton implies creation/destruction entirely private
    Factory():_associations(std::map<std::string,CreateFunc>()) {}

    //! Factory declared private to avoid bad surprises
    Factory(const Factory&);

    //!operator= declared private to avoid bad surprises
    Factory& operator=(const Factory&);

    ~Factory() {}

    //! associations_ contains the correspondance between std::strings and objects
    AssocMap _associations;

};

#define DECLARE_CONSTITUTIVE_LAW(CLASS_NAME,KEYWORD)                    \
    namespace {                             \
    AbstractConstitutiveLaws* creator(){ return new (CLASS_NAME);}  \
    const std::string kwords(KEYWORD);              \
    const bool registered = Factory<AbstractConstitutiveLaws>::Instance().Register(kwords,creator); \
    }
0

There are 0 answers