2013-05-06 46 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; 
//       ^^^^^^^^