2

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

newbie
  • 154
  • 7
  • Do you want a single instantiation as A + B, but not A + B together with A + B ? –  Nov 28 '14 at 17:57
  • You need to provide an actual use case. – Captain Obvlious Nov 28 '14 at 18:34
  • @DieterLücking, I just want both A and B to have the same type, they can be A and B or A and B and B, i.e. A and B must be instantiated with the same type. – newbie Nov 28 '14 at 18:41
  • @newbie: What about multiple matching pairs? –  Nov 28 '14 at 18:51
  • @CaptainObvlious, an actual use case can be something like this: A is a row of a file, B is the file parser. In B, you may have A getRow(const int rowIndex) and you want both the parser and the row read from the file to have exactly the same type. – newbie Nov 28 '14 at 19:00
  • There is no use case in your post, just a desire. – Captain Obvlious Nov 28 '14 at 19:02
  • @DieterLücking, A and B do not have to be instantiated at the same time. How would you implement the matching pairs? Thanks. – newbie Nov 28 '14 at 19:15
  • @CaptainObvlious, see my comment above. – newbie Nov 28 '14 at 19:16

2 Answers2

7

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;
zdan
  • 28,667
  • 7
  • 60
  • 71
  • In addition the constructors of A and B could be private and C could be a friend of both, holding actually two members A and B. –  Nov 28 '14 at 18:27
  • thanks @DieterLücking, but what is the benefit of doing that? It does not make the code look more elegant? – newbie Nov 28 '14 at 18:36
  • @newbie It would prevent users of A or B from accessing them directly and violating this constraint. – zdan Nov 28 '14 at 19:00
0

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
};