0

Following is a simple example.

template <typename TA>
class A {

};

template <class A>
class B {
    A a;
    A::TA ta;
};

int main(){
    B<A<int> > b;
}

where, I have a template class A with a unknown type (TA) as template parameter. In class B, I want to define some variables using class A and its member type.

I got an error message during compilation, as follows.

error: need typename before ˜C1::T1˜ because ˜C1˜ is a dependent scope

I know I can do something like this,

template <class A, typename TA>
class B{
    A a;
    TA ta;
};

But it seems an ugly format.

Is the first case possible? Thanks.

user9985127
  • 175
  • 5

2 Answers2

1
template <typename TA>
class A {
public:
    using type = TA;
};

template <class A>
class B {
public:
    A a;
    typename A::type ta;
};

Does this help?

StackExchange123
  • 1,871
  • 9
  • 24
  • This declares a variable in class `A` for no reason. You can use `using type = TA;` in `A` instead and then use it as `typename A::type ta;` in `B`. – super May 22 '20 at 08:22
0

An instantiation of your A template does not have any members. The template parameters aren't exposed outside the definition.

It's not clear if you want to use any type in B, or only instantiations of A. The latter is easier. Currently you are hiding the definition of A with your template parameter.

template <typename TA>
class A {
public:
};

template <typename TA>
class B {
public:
    A<TA> a;
    TA ta;
};

If you want to access the template parameters, A will need to expose them itself.

template <typename TA>
class A {
public:
    using some_name = TA;
};

Now B can use any type that has a some_name member type.

template <typename A>
class B {
public:
    A a;
    typename A::some_name ta;
};
Caleth
  • 52,200
  • 2
  • 44
  • 75