views:

55

answers:

2

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 pointers 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.

+1  A: 
template<typename T, typename U>
void doSomething ( Temp< T > * a, Temp< U> * b ) 
{ 
    (*a) = (*b); 
}; 
James Curran
Temp<t> and Temp<U> are completely different types, aren't they? Wouldn't that make the assignment line impossible?
San Jacinto
At compile time the compiler will create a version of doSomething with the concrete types specified, and then attempt to compile the resultant function. In this case it will work, as the assignment between the specified types of U and T is valid.
Visage
@Visage my question is more regarding the assignability of a Temp<U>* to a Temp<T>*. This probably has nothing to do with doSomething(), in my mind. Where I am wrong? Thanks.
San Jacinto
James Curran
@James, yes in your last sentence you are re-stating my question. If a is a Temp<A> star and b is a Temp<B> star, are they EVER compatible in this manner? Does it follow that because an A start can be assigned a B star that a Temp<A> star can be assigned a Temp<B> star?
San Jacinto
@San Jacinto: That would depend on the assignment operator of `Temp<>`
James Curran
A: 

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.).

San Jacinto