2012-01-22 37 views
3

我想使用以下結構C++,模板化T IN的std ::對<T, short>

template <typename T> 
struct TPair 
{ 
typedef std::pair <T, short> Type; 
}; 

到模板化「第一」的std ::對類型和創建這樣對一個矢量。

template <typename T> 
struct TPairs 
{ 
typedef std::vector <TPair <T> > Type; 
}; 

但這個代碼似乎被擰爲了共同使用,這是不舒服:

TPair <double> ::Type my_pair (1.0, 0); //Create pairs 
TPair <double> my_pair2 (1.0, 0); //Create object, needs a constructor 

TPairs <double> ::Type pairs; //Create vector 
TPairs <double> pairs2; //Create object 

pairs.push_back(my_pair); //Need a constructor 
pairs2.push_back(my_pair); //No push_back method for the structure... 
.... 

有沒有更簡單舒適的解決方案?

+0

此外,你不應該''typedef''定義'對'的'vector',你從而沒有聲明一個向量,而是一個別名類型。 –

+1

@泰勒先生:我認爲這是故意的。我認爲OP需要一個「typedef模板」。我認爲這些被添加到C++ 11的標準中。 –

回答

3
template <typename T> 
struct TPairs 
{ 
    typedef std::vector <TPair <T> > Type; 
}; 

這裏有一個問題:你要創建一個類型是TPair<T>一個向量,這實際上是不是你想要的。你想要一個向量TPair<T>::Type

template <typename T> 
struct TPairs 
{ 
    typedef std::vector <typename TPair <T>::Type > Type; 
}; 

至於你的使用情況,請記住,您創建這兩個結構在那裏只是爲了模擬一個模板的typedef,你永遠不應該實例化他們所有,只是用自己的Type成員的typedef。所以:

TPair <double> ::Type my_pair (1.0, 0); // Good, creates a std::pair 
TPair <double> my_pair2 (1.0, 0); // Not good, does not create an std::pair 


TPairs <double> ::Type pairs; //Good, creates a vector 
TPairs <double> pairs2;  //Not good, doesn't create a vector 

pairs.push_back(my_pair); // Ok, does what you mean 
pairs2.push_back(my_pair); // Can't compile, the `TPairs` struct ins't a vector 
+2

)您可以將私有構造函數添加到「包裝」類型。 –

+0

@ mat:感謝您的擴展和示例,它工作正常。更簡單的結構,我不得不等待一段時間(也許VS 2012 :-))) – justik

3

這聽起來像是你想要一個「template alias」,它顯然是用C++ 11添加到標準中的。你的情況的語法會是這樣的:

template <typename T> 
using TPair = std::pair<T,short>; 

template <typename T> 
using TPairs = std::vector<TPair<T>>; 

[聲明:我沒有嘗試這樣做,所以它可能是廢話。]

+0

+1。這是正確的,奧利。這不是「無稽之談」。 – Nawaz

+0

@ Oli:謝謝,但是VS2010仍然不支持此功能:-( – justik

1

爲什麼不簡單使用繼承? 例如:

template <typename T> 
struct TPair : public std::pair< T, short >{}; 

template <typename T> 
struct TPairs : public std::vector< TPair<T> > {}; 
0

如果你喜歡冒險的感覺,你可以從你想模板化,並提供適當的構造函數的類型繼承。 :)

#include <utility> // forward 

template<class T> 
struct TPair 
    : public std::pair<T, short> 
{ 
private: 
    typedef std::pair<T, short> base; 

public: 
    template<class U> 
    TPair(U&& u, short s) // forwarding ctor 
    : base(std::forward<U>(u), s) {} 

    TPair(TPair const& other) // copy ctor 
    : base(static_cast<base const&>(other)) {} 

    TPair(TPair&& other) // move ctor 
    : base(static_cast<base&&>(other)) { 

    // and assignment operators... I'll leave those as an exercise 
}; 

// and the same for TVector... again, I'll leave those as an exercise. :> 
+0

@ Xeo:一個有趣的解決方案... – justik

相關問題