Dam Dam - 4 years ago 61
C++ Question

Declaring variable inside a class with templated class type given template parameter

I am trying to instantiate a template class contained in a class which is given as a template parameter. This might be easier to understand with an example :

struct A {
static constexpr int a = 42;

class B {
int b;
};

template<typename X>
class C {
X c;
};
};

template<typename U, typename T>
class D {
int a = U::a;

using B = typename U::B;
B b;

//using C = typename U::C;
// C<T> c;
A::C<T> e;
};


int main(void) {
D<A, int> d;
return 0;
}


If I uncomment the commented lines, the compiler gives me an error which says C is not a template. I tried other approaches to instantiate this variable, but it didn't work. I would like to have the equivalent of the e variable but using the U typename.

Answer Source

Note you didn't declare C as a template type, then C<T> c will cause the error because you can't use it as a template type.

What you want is alias template (a name for a family of types), the correct syntax is:

template <typename Z>
using C = typename U::template C<Z>;

then

C<T> c;  // same as U::template C<T>; Z is substituted with T 

With D<A, int> d;, U = A and T = int, then C<T> inside D is same as A::C<int>.

LIVE

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download