一致的模板类型

fle*_*ser 5 c++ templates

问题

考虑以下课程

template <typename T>
struct A
{
   T x;
};
Run Code Online (Sandbox Code Playgroud)

现在,另一个类是这样的模板:

template <typename T, typename U>
class B
{
   protected:
      std::vector<U> arr;

   public:
      T get_x(unsigned int p) { return arr[p].x; }
};
Run Code Online (Sandbox Code Playgroud)

我想A<T>::x从内部访问该字段B<T, A<T>>::get_x()并将其保持不变(即保持其类型T).我对模板的不了解说,这需要知道T它的类型和它应该是模板参数之一class B.然而,这使得可以声明不一致的东西,例如B<int, A<double>>,并且通常听起来像是不必要的重复.

问题

  1. 我写的是一个糟糕的编程实践的例子吗?怎么写呢?
  2. 有推断类型的可能性TA<T>::x,避免两个模板类型?感觉就像是重复,所以我不确定是否有一个敬畏上帝,标准持久的解决方案.

对于它的价值,我使用GCC 4.6.2和-std = c ++ 0x.

Naw*_*waz 4

我建议标准库采用一种方法。定义嵌套类型。

template <typename T>
struct A
{
   typedef T value_type; //this is nested type to be used by B
   T x;
};

//this is another class added by me, just to demonstrate the genericity
template <typename T>
struct C
{
   typedef T value_type; //this is nested type to be used by B
   T x;
};

template <typename T>
class B
{
      typedef typename T::value_type value_type;  //get the nested type
   protected:
      std::vector<T> arr;

   public:
      value_type get_x(unsigned int p) { return arr[p].x; }
    //^^^^^^^^^ note this
};
Run Code Online (Sandbox Code Playgroud)

用法:

 B<A<int>> ba;    //'>>' if C++11, otherwise use '> >' (separate them by space)
 B<C<double>> bc; //works for C class template as well
Run Code Online (Sandbox Code Playgroud)

  • 哦,这就是为什么 boost 会这样定义模板类型!很棒的见解,谢谢! (3认同)