2013-10-12 80 views
1

我有一個工廠類註冊類型如何正確註冊?

class Factory 
{ 
public: 
    template<class T> 
    static void regist() 
    { 
     mMap[T::type()] = [](){return new T();}; 
    } 

    static Base* create(string type) 
    { 
     ... // use map to find the function to create a new object 
    } 

private: 
    static map<string, function<Base*()>> mMap; 
}; 

map<string, function<Base*()>> Factory::mMap; 

和基地

class A : public Base 
{ 
public: 
    static string type() { return "A"; } 
    static bool sRegist; 
    A() {} 

}; 

bool A::sRegist = []() -> bool { 
    Factory::regist<A>(); 
    return true; 
}(); 

的具體T類然而,當運行該代碼崩潰。我認爲這是由於靜態成員的無限初始化順序。如何使它工作?謝謝。

回答

1

廣場mMap靜態函數內部,就像這樣:

class Factory 
{ 
public: 
    template<class T> 
    static void regist() 
    { 
    getMap()[T::type()] = [](){return new T();}; 
    } 

    // ... 

private: 
    static map<string, function<Base*()>>& getMap() { 
    static map<string, function<Base*()>> mMap; 
    return mMap; 
    } 
}; 

在這種情況下,mMap將盡快函數被調用初始化。

+0

非常聰明。我的第一個評論來自你的早期答案。 – user1899020