Access to parameter passed to template object

Imagine we have the follwing templated classes

template <class T>
struct A {
    T a;
};

template <class T>
struct B {
    T b;
};

int main (){
    B< A<double> > obj;
}

What if class B needs to know the type T that was use to build class A? (In this case it was double)

The trick is to define a new type inside class A, that can be acessed by class B, like this:

template <class T>
struct A {
    T a;
    typedef T my_type;
};

template <class T>
struct B {
    T b;
    typename T::my_type c;
};

int main (){
    B< A<double> > obj;
}

The need for the extra typename keyword is explained here.

Reference: http://stackoverflow.com/questions/301203/extract-c-template-parameters

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s