How to make multiple template class to have the same type

2.1k views Asked by At

There are two template class A and B. How to enforce them to be instantiated to the same type without nesting one with another? e.g. If I define the two class like the following:

template <class T> 
class A {};

template <class T> 
class B {};

Then it is possible that the user may do something like this A<int> a; and B<float> b;

I would like to force A and B to have exactly the same type, but I do NOT want them to be nested within each other. So when someone uses these two class, A and B must have the same type. Is there any way to do that? And what is a good practice to design class like these?

Thanks

2

There are 2 answers

3
zdan On BEST ANSWER

You don't have to nest them in one another, but you could nest them within a third type:

template<class T>
struct C {

    typedef A<T> A;
    typedef B<T> B;

};

Client just access via C:

C<T>::A a;
C<T>::B b;
0
Gaurav Kandoria On

if you are planning to use variable of one class inside another class, you can do something like this,

template <class T> 
class A {
//code 
};

template <class U> 
class B {
//code
A<U> a; 
//remaining code
};