2014-06-18 136 views
0

我正在嘗試使用this answer中的概念實現一個簡單的插件管理器。我將它作爲模板實現,以便我可以爲不同的管理器實例化不同接口的插件。在模板中使用模板參數作爲參數

但是,我無法得到它編譯。

這裏是演示了該問題的摘錄:

#include <map> 
#include <string> 

template<typename InterfaceType> 
class PluginManager { 

public: 
    // Map between plugin name and factory function 
    typedef std::map<std::string, InterfaceType*(*)()> map_type; 

    static InterfaceType *createInstance(std::string const& plugInName) { 
     map_type::iterator iter = map().find(plugInName); 
     if (iter == map().end()) 
      return 0; 
     return iter->second(); 
    } 

protected: 
    static map_type & map() { 
     static map_type map; 
     return map; 
    } 

}; 

class MyInterface {}; 

PluginManager<MyInterface> myInterfacePluginManager; 

int main(int argc, char *argv[]) { 
} 

當試圖編譯它,這是發生了什麼:

$ g++ pimgr_bug.cpp 
pimgr_bug.cpp: In static member function ‘static InterfaceType* PluginManager<InterfaceType>::createInstance(const std::string&)’: 
pimgr_bug.cpp:12: error: expected ‘;’ before ‘iter’ 
pimgr_bug.cpp:13: error: ‘iter’ was not declared in this scope 
pimgr_bug.cpp:15: error: ‘iter’ was not declared in this scope 

這似乎是與map_type的定義:如果我改變它,以便map值類型是它編譯好的一些具體類,但是值類型定義爲InterfaceType*(*)()或實際上與InterfaceType相關的任何東西,則它不起作用。該映射應該保持插件名稱和指向相應工廠函數的指針之間的映射。

我幾乎可以肯定缺少對模板語法的一些基本理解!

當然,是否有可能在一個模板中創建一個映射,其中包含由模板參數之一定義的類型?

我正在使用gcc 4.4.7,不幸的是不能使用C++ 11(如果這是相關的)。

謝謝!

+0

嘗試添加「typename」,即「typename map_type :: iterator」。 –

+0

gcc 4.8提供了一個更有用的錯誤信息:*因爲'PluginManager :: map_type'是一個相關範圍,所以在'PluginManager :: map_type :: iterator'之前需要'typename' * – Walter

+0

@MichaelAaronSafyan修復了它。 ..如果這不是重複請添加作爲答案 – harmic

回答

0

map_type::iterator是從屬名稱,因爲map_type依賴於模板參數(InterfaceType)。 隨後,編譯器不會假定map_type::iterator命名一個類型,除非您明確說出*。

因此,寫

typename map_type::iterator iter = map().find(plugInName); 

它應該編譯就好了。

* 或名稱查找找到一個,但這不適用於此。