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?
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.
Easy way out: specialise L<>
so that L<B>
inherits from L<A>
:
template<>
struct L<B> : public L<A> {};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With