Compatible Template Types

Problem

Consider the following class

template <typename T>
struct A
{
   T x;
};

Now another template is templated like this:

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

   public:
      T get_x(unsigned int p) { return arr[p].x; }
};

I would like to access the field A<T>::xfrom B<T, A<T>>::get_x()and return it without changes (i.e. save its type as T). My poor knowledge of templates says that this requires knowledge of the andof type T, it should be one of the template parameters class B. However, this allows you to declare something inconsistent, for example B<int, A<double>>, and generally sounds like an unnecessary repetition.

Questions

  • Did I write an example of bad programming practice? How should this be written?
  • Is it possible to infer a type Tfrom A<T>::xand avoid two types of patterns? This seems like a repetition, so I'm not sure if there is a god-fearing, standard solution or not.

, GCC 4.6.2 -std = ++ 0x.

+5
1

, . .

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
};

:

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

All Articles