Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers to class templates with different template parameters [closed]

I got this question on the interview and still have no idea how to solve it:

Let say we have a C++ code:

int main(int argc, char* argv[])
{
    L<A>* pA = 0;
    L<B>* pB = 0;
    pA = pB;
}

What should we add so this actually compiles?

In other words, how should we define L, A and B classes? Please do not use preprocessor's directives.

I have only idea how to solve it:

template<class T> struct L {};
struct A {};
typedef A B;

Or even simplier with forward declarations:

struct A;
typedef A B;
template<class> struct L;

Any other ideas?

like image 505
Sashaka Avatar asked Sep 20 '12 15:09

Sashaka


3 Answers

No preprocessor directives:

/* <-- added line

int _tmain(int argc, _TCHAR* argv[])
{
    L<A>* pA;
    L<B>* pB;
    pA = pB;

    return 0;
}

*/ //<-- added line

int main()
{
}

works fine for me.

like image 131
Luchian Grigore Avatar answered Sep 24 '22 17:09

Luchian Grigore


Easy way out: specialise L<> so that L<B> inherits from L<A>:

template<>
struct L<B> : public L<A> {};
like image 45
Gorpik Avatar answered Sep 25 '22 17:09

Gorpik


The L<A>* should be assignable from L<B>*, meaning that L<B> should be a subclass of L<B>.

This is not so trivial. Maybe A and B should implement some traits concept, which the L template can use:

template<typename E> struct L : public L< typename E::base >
{
};

struct BASE {};
template<> struct L<BASE> {};

struct A : public BASE {
  typedef BASE base;
};

struct B : public A {
  typedef A  base;
};

EDIT -- compiling versio on http://codepad.org/CT3FvmwQ

like image 33
xtofl Avatar answered Sep 22 '22 17:09

xtofl