2013-05-06 45 views
0

不幸的是我正在使用C++ 98。創建模板和基於boost :: shared_ptr的通用工廠編譯時出錯

template <class bT> 
class Creator 
{ 
public: 
    virtual bT* create() = 0; 
}; 

template <class bT> 
struct CreatorPtr 
{ 
    typedef boost::shared_ptr< Creator<bT> > ptr; 
}; 

template <class bT, class cT> 
class CreatorImpl : public Creator<bT> 
{ 
public: 
    virtual bT* create() { return new cT; } 
}; 

template <class bT> 
class Factory 
{ 
public: 
    virtual bT* create(const std::string& name) = 0; 
    virtual ~Factory() { _table_creator.clear(); } 
protected: 
    Factory() {} 
    Factory(const Factory&) {} 
    Factory &operator=(const Factory&) { return *this; } 
    void registerCreator(const std::string& name, typename CreatorPtr<bT>::ptr creator) 
     { _table_creator[name] = creator; } 
    typedef std::map<std::string, typename CreatorPtr<bT>::ptr> tableCreator; 
    typedef typename tableCreator::const_iterator citerTc; 
    ...... 
protected: 
    tableCreator _table_creator; 
}; 

我有錯誤

"error: expected nested-name-specifier before ‘tableCreator’" on the "typedef typename tableCreator::const_iterator citerTc;" line. I am using 4.1.2 g++."

對不起大家,我錯過了類型名在這裏「由SYAM指出」在citerTc的定義中刪除模板。現在代碼編譯並運行良好。 謝謝大家的幫助。

回答

2

既然你有一個合格的,依賴的類型名稱,您需要使用typename消歧告訴編譯器解釋::後隨之而來的類型(而不是數據成員)的名稱:

typename CreatorPtr<bT>::ptr // ptr is the name of a type, so you need 
// ^^^^^^^^      // to use the "typename" keyword in order 
           // to let the compiler parse it correctly 

因此,例如:

void registerCreator(const std::string& name, 
        typename CreatorPtr<bT>::ptr creator) 
//     ^^^^^^^^ 

同理:

typedef std::map<std::string, typename CreatorPtr<bT>::ptr> tableCreator; 
//       ^^^^^^^^