C ++,在std :: pair <t,short =“”> </t,>中模板化T.

时间:2012-01-22 11:23:14

标签: c++ templates std-pair

我想使用以下构造来模板化“第一”类型的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 个答案:

答案 0 :(得分:3)

听起来你想要一个“template alias”,这显然是用C ++ 11添加到标准中的。您的案例中的语法类似于:

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

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

[免责声明:我没试过,所以这可能是胡说八道。]

答案 1 :(得分: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 :(得分:1)

为什么不简单地使用继承? 例如:

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

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

答案 3 :(得分: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. :>
相关问题