2011-03-10 50 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