2012-06-17 21 views
0

所以我希望能夠在初始化時調用一個函數。這是一個無效函數,但我希望在調用時間main()的副作用(在這種情況下更新工廠函數表)到位。現在我做的是剛剛返回一個int和初始化它一個靜態變量:程序初始化時的調用函數

//Factory inherits from FactoryBase 
class FactoryBase 
{ 
    ... 
private: 
    static std::unordered_map<std::string, FactoryBase*> factoryTable; 
public: 
    template<class C> 
    static int addClass(const std::string& name) 
    { 
     factoryTable[name] = new Factory<C>; 
     return 0; 
    } 
}; 
... 
int Foo::uselessStaticInt = FactoryBase::addClass<Foo>("foo"); 
//class Foo is now associated with the string "foo" 

有沒有一種方法,我可以調用靜態函數,而無需一個靜態的詮釋?

我可以張貼在工廠類的完整的源代碼,但什麼我更感興趣的是編譯時或初始化時的函數調用

+1

怎麼可能固有的動態結構(像'unordered_map')在編譯時被填充? –

+5

我想你的意思是說在程序初始化時(在main()之前),而不是在編譯時。 – interjay

+0

是的。基本上在初始化時,儘管它在功能上與編譯時無法區分。固定。 – Lucretiel

回答

1

正如正確地指出的@interjay你實際上是調用你的函數在初始化時(靜態對象被初始化的時間),而不是在編譯時。如果沒有靜態對象,AFAIK將無法做到這一點。你可以這樣做在一些靜態的物體,雖然這可能使該代碼的構造看起來稍微簡單:

ClassRegister<Foo> fooRegister("foo"); // Call FactoryBase::addClass<Foo>("foo") 
             // in the constructor of ClassRegister<Foo> 
0

我經常使用的一個輔助registrator類,有一個單一的全球實例一起:

頭文件FactoryBase.hpp

template <typename T> struct Registrator 
{ 
    explicit Registrator(char const * s) 
    { 
     FactoryBase<T>::addClass(s); 
    } 
}; 

(這可能是FactoryBase公共嵌套類,如果你喜歡。)

翻譯單位:

#include <FactoryBase.hpp> 
#include <Foo.hpp> 

namespace 
{ 
    Registrator<Foo> fooRegistrator("foo"); 
} 
相關問題