I have a class that looks like this:
class Base
{
public:
Base( int val = 0 ) : value( val ) {};
int value;
};
Classes A
and B
inherit Base
:
class A : public Base {};
class B : public Base {};
I also have a templated class with a signature similar to:
template < class T >
class Temp
{
public:
Temp ( const T & val = T() ) : m_T( val ) {};
T m_T;
};
What I am trying to do is have a function that takes pointer开发者_JS百科s to Temp<Base>
instances and act upon them:
void doSomething ( Temp< Base > * a, Temp< Base > * b )
{
(*a) = (*b);
};
Ultimately, I would like to have Temp<A>
and Temp<B>
instances passed to doSomething()
, like:
void
main()
{
Temp<A> a;
Temp<B> b;
doSomething( &a, &b) ;
};
Obviously, this will not work because Temp<A>
and Temp<B>
are not related and there is no implicit conversion between the types (even though A
and B
are Base
).
What are some of the ways this problem could be solved? Any input would be greatly appreciated.
Thanks in advance for your help.
template<typename T, typename U>
void doSomething ( Temp< T > * a, Temp< U> * b )
{
(*a) = (*b);
};
You lose a lot of the usefulness of the inheritance relationship if you aren't careful, but if you make Temp derive off of a common base class, you can create templated members in its derived classes. What you essentially end up doing is moving your common interface of A and B into BASE, and then for specialization (how to actually carry out those functions), you refer to the TempA or TempB member in BASE (with A and B surrounded by the brackets. Editor won't le me be explicit.).
精彩评论