3

次の構造を使用して、「最初の」タイプのstd::pairをテンプレート化したい

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

そして、そのようなペアのベクトルを作成します。

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...
....

もっとシンプルで快適な解決策はありますか?

4

4 に答える 4

4

どうやらC++11で標準に追加された「テンプレートエイリアス」が必要なようです。この場合の構文は次のようになります。

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

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

[免責事項:私はこれを試したことがないので、ナンセンスかもしれません。]

于 2012-01-22T11:34:00.843 に答える
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;
};

ユースケースに関しては、作成した2つの構造体はテンプレート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
于 2012-01-22T11:45:32.490 に答える
1

なぜ単純に継承を使用しないのですか?例えば:

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

template <typename T> 
struct TPairs : public std::vector< TPair< T > >  {};
于 2012-01-22T12:18:32.913 に答える
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. :>
于 2012-01-22T12:26:49.187 に答える