0

我们正在尝试将我们的代码转换为库,以允许与其他代码进行一些接口。在代码中,我们使用了很多依赖于单例模式的对象工厂,其中对象通过宏声明,实现如下。

我们的问题是,当我们将整个代码编译为库时,对象不再在工厂中注册,并且无法在执行时创建。你有什么建议吗?值得注意的是,应该做一些事情 extern 吗?我必须承认我已经达到了我的极限......

非常感谢 !

马克

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); \
    }
4

0 回答 0