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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With