2011-03-10 51 views
4

我需要创建一个包含多索引容器作为存储的泛型类。当我编译时,它会给出错误,如下所示,我已经定义了第n个索引视图。模板参数来提升多索引容器

错误:非模板“nth_index”作为模板


/** 
* connection manager 
*/

template < typename T, typename C > class conn_mgr: boost::noncopyable { public: /** * connection ptr */ typedef boost::shared_ptr conn_ptr_t;
/** * connection table type * It's a multi index container */ typedef boost::multi_index::multi_index_container < conn_ptr_t, boost::multi_index::indexed_by < //sequenced < >, boost::multi_index::hashed_unique < BOOST_MULTI_INDEX_CONST_MEM_FUN(T, std::string, T::id) >, boost::multi_index::hashed_non_unique < BOOST_MULTI_INDEX_CONST_MEM_FUN(T, std::string, T::type)>, boost::multi_index::hashed_non_unique < boost::multi_index::composite_key < conn_ptr_t, BOOST_MULTI_INDEX_CONST_MEM_FUN(T, std::string, T::id), BOOST_MULTI_INDEX_CONST_MEM_FUN(T, std::string, T::type) > > > > conn_table_t;

//typedef for ConnectionIdView 
typedef conn_table_t::nth_index<0>::type conn_table_by_id_type; 

typedef conn_table_t::nth_index<1>::type conn_table_by_type; 

typedef conn_table_t::nth_index<2>::type conn_table_by_id_type; 

私人: conn_table_t conn_table_; };

and here how I am using in main.

int main(int argc, char** argv) { typedef conn_mgr < smpp_conn, smpp_config > smpp_conn_mgr_t; smpp_conn_mgr_t conn_mgr; }

+1

您无法键入一个模板。此行无效:'typedef boost :: shared_ptr conn_ptr_t;' – 2011-03-10 05:34:40

回答

11

使用此语法,而不是你的嵌套的typedef:

typedef typename conn_table_t::template nth_index<0>::type conn_table_by_id_type; 

typename关键字在这里被用作一个限定词让编译器知道conn_table_t::template nth_index<0>::type是一种类型。 typename的这种特殊用途仅在模板中是必需的。

template关键字在此处用作其他名称的distingush成员模板的限定符。


此外,该行是无效的:

typedef boost::shared_ptr conn_ptr_t; 

你不能的typedef模板。你只能使用typedef类型。也许你的意思是写:

typedef typename boost::shared_ptr<T> conn_ptr_t; 

最后一个错误:您正在尝试获得两种类型定义了同一个名字:conn_table_by_id_type


您应该使用BOOST_MULTI_INDEX_CONST_MEM_FUN(T, std::string, id)而不是BOOST_MULTI_INDEX_CONST_MEM_FUN(T, std::string, T::id),如记录here


在回答你的最后的评论:这段代码编译为我:

void foo(std::string id) 
{ 
    conn_table_by_id_type& id_type_view = conn_table_.template get<0>(); 
    typename conn_table_by_id_type::const_iterator it = id_type_view.find(id); 
} 

哪里fooconn_mgr模板中的成员函数。我猜测以上就是你想要做的。

您应该编写帮助程序方法,以获得对三个不同conn_table_索引的引用。这将使事情更加简洁。例如:

conn_table_by_id_type & by_id_type() {return conn_table_.template get<0>();} 

void foo2(std::string id) 
{ 
    typename conn_table_by_id_type::const_iterator it = by_id_type().find(id); 
} 
+0

Emile,thx很多。我还学习了使用typename的一课。例如。当我尝试std :: vector :: iterator时,它给出错误,但是一旦我转换为typename std :: vector :: iterator,它就工作了。 – rjoshi 2011-03-10 13:10:14

+0

嗨Emile,现在当我使用conm_mgr类,如上所示,我得到错误“没有类型名为”T“在类smpp_conn。我传递”smpp_conn“类对象作为第一个模板参数”T“在conn_mgr类 – rjoshi 2011-03-10 13:57:47

+0

@ rjoshi:请参阅修订后的答案。 – 2011-03-10 15:03:48