Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consistent template types

Tags:

c++

templates

Problem

Consider the following class

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

Now, another class is templated like so:

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>::x from within B<T, A<T>>::get_x() and return it unaltered (i.e., keep its type as T). My poor knowledge of templating says that this requires knowing the type andof T it should be one of the template parameters of class B. However, that makes it possible to declare something inconsistent, like B<int, A<double>>, and in general sounds like an unnecessary repetition.

Questions

  1. Is what I wrote an example of bad programming practice? How should this be written?
  2. Is there a possibility of inferring the type T of A<T>::x and avoid two template types? It feels like a repetition, so I am not sure if there is a God-fearing, standard-abiding solution out there or not.

For what it is worth, I am using GCC 4.6.2 with -std=c++0x.

like image 936
fledgling Cxx user Avatar asked Oct 09 '22 10:10

fledgling Cxx user


1 Answers

I would suggest an approach adopted by the Standard Library. Define a nested type.

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

Usage:

 B<A<int>> ba;    //'>>' if C++11, otherwise use '> >' (separate them by space)
 B<C<double>> bc; //works for C class template as well
like image 59
Nawaz Avatar answered Oct 13 '22 10:10

Nawaz