2013-04-30 74 views
2

我想知道是否有可能有某種參數化的typedef。參數化typedef可能嗎?

爲了說明這一點,在我的代碼我這個typedef:

typedef std::queue<std::vector<unsigned char>, std::deque<std::vector<unsigned char> > > UnsignedCharQueue; 

正如你可以看到這是一個相當笨重的結構使的typedef纔有意義。但是,如果我想要使用其他數據類型的隊列,我需要事先定義它們。

所以我在想如果有可能使用這樣的結構:

typedef std::queue<std::vector<T>, std::deque<std::vector<T> > > Queue<T>; 

private: 
    Queue<unsigned char> mMyQueue; 

類似像Java泛型。

+1

[C++ template typedef]的可能重複(http://stackoverflow.com/questions/2795023/c-template-typedef) – 2013-04-30 18:40:26

回答

9

在C++ 11,您可以使用模板的別名,如:

template<typename T> 
using my_alias = some_class_template<T>; 

// ... 
my_alias<T> obj; // Same as "some_class_template<T> obj;" 

所以你的情況這將是:

template<typename T> 
using Queue = std::queue<std::vector<T>, std::deque<std::vector<T> > >; 

還要注意,在C++中

template<typename T> 
using Queue = std::queue<std::vector<T>, std::deque<std::vector<T>>>; 
//                ^^^ 

在C++ 03你可以定義:11,如下所示你不需要離開封閉尖括號之間的空間,所以上述可改寫一個Queue元函數是這樣的:

template<typename T> 
struct Queue 
{ 
    typedef std::queue<std::vector<T>, std::deque<std::vector<T> > > type; 
}; 

,你會再使用這種方式:如果你正在使用它的模板與參數T(如下所示),不要忘了

Queue<int>::type obj; 

typename消歧:

template<typename T> 
struct X 
{ 
    typename Queue<T>::type obj; 
// ^^^^^^^^ 
} 
+0

該死,你閃電般快。我打算髮布這個。 – 2013-04-30 18:40:13

+0

@ H2CO3:我很幸運能夠儘早得到新的問題通知;) – 2013-04-30 18:40:44

+0

@AndyProwl:通知? – 2013-04-30 18:41:18

2

是的,它的工作原理是這樣的:

template <typename T> using Queue = std::queue<std::vector<T>, std::deque<std::vector<T> > >; 
+0

g ++ c Devolus 2013-04-30 21:14:24

+0

@Devolus:使用g ++時,請確保將-std = C++ 11指定爲命令行參數之一。 – 2013-04-30 22:18:26

+0

我試過這個開關,但它不能識別它。 – Devolus 2013-05-01 06:26:20