2010-02-10 86 views
2

我有一個類看起來像這樣:C++模板類

#include <vector> 
#include "record.h" 
#include "sortcalls.h" 

template< 
    typename T, 
    template<typename , typename Allocator = std::allocator<T> > class Cont = std::vector> 
class Sort: public SortCall { 

此代碼工作,我打電話像這樣從其他類:

Comparator c; // comparison functor 
Sort< Record, std::vector > s(c); 

現在我希望能夠將容器切換到另一個容器,比如列表。 所以我認爲typedef會很整齊。它應該是這樣的

typedef std::vector<Record> container; // Default record container 

template< 
    typename T, 
    template< typename, typename container > // ??? 
class Sort: public SortCall { 
+1

我不確定我是否理解;你沒有在任何地方使用'排序'。另外,'_Alloc'保留給編譯器;你應該改變它爲'Allocator'或者其他東西。 – GManNickG 2010-02-10 21:54:28

+1

我不確定我明白爲什麼模板參數必須這麼複雜。爲什麼不用'template class Sort ...'用'Sort s''? – UncleBens 2010-02-10 22:05:06

+0

@GMan thx。改變了它。 – mre 2010-02-10 22:06:49

回答

5

不要使用模板模板參數(在你的代碼),他們是脆弱和不靈活。使用綁定機制,如果你需要(標準::分配器就是一個例子),但在這種情況下,不要:

template<class T, class Cont=std::vector<T> > 
struct Sort { 
    typedef Cont container_type; // if you need to access it from outside the class 
    // similar to std::vector::value_type (which you might want to add here too) 
}; 

typedef Sort<int, std::list<int> > IntListSort; 

比較到std ::隊列和std ::棧,這也遵循這一模式。

+0

在模板模板參數中使用這種設計是我們很多人難以瞭解的事情之一,其中很多人眯着眼睛看着標準和頭部的劃痕。 +1。 – 2010-02-10 22:19:08

+0

這可能是未來發展的最佳解決方案。你得到我的投票。雖然UncleBens提供了第一個工作解決方案。 Thx所有! – mre 2010-02-10 22:34:23

0

你應該能夠在typename後面直接使用'container',就像你在你的例子中那樣。編譯器運行時,它的類型規範會被擴展。

嘗試編譯它...

0

我想,如果你使用型特徵可能更容易。 STL和boost中的每個容器都有數字off typedef,其中value_type(請參閱參考文獻http://www.cplusplus.com/reference/stl/vector/)。 所以,你的代碼可能看起來像:

template<class C> 
class sort { 
    typedef typename C::value_type value_type; // equivalent to T in your case. 
    // similarly you can get allocator, iterator, etc.