justik
justik

Reputation: 4265

C++, copy constructor implementation, default templates parameters

First I apologize for a somewhat longer sample code and question... There are three classes A, B, C (where A and B are abstract).

The class A represents a container storing objects of different types Item.

template <typename Item>
struct TList {typedef std::vector <Item> Type;};

template <typename Item>
class A
{
protected:  typename TList <Item>::Type items;
            A() : items ( 0 ) {}
            virtual ~A() = 0 {}
};

The derived class B contains a specialization for Item* with some additional functionality and has a default parameter of TD.

typedef enum { D1, D2} TD;

template < typename T, const TD td = D1 >
class B;

template <typename Item, const TD td>
class B <Item *, td> : public A <Item *>
{
    public:
            B () : A <Item *> () {}

    template <const TD td2>
    B ( const B <Item *, td2> & source )
    {
        if ( this != &source ) { //Code } //Error
    }

    virtual ~B() = 0 {}  
};

The class C is not abstract and contains another added functionality (not included in the code).

template < typename T, const TD td = D1 >
class C;

template <typename Item, const TD td>
class C <Item *, td> : public B <Item *, td>
{
    public:
            C() : B <Item *, td> () {}

    template <const TD td2>
    C ( const C <Item*, td2 > &source ) : B  <Item*, td> ( source ) {}     
};

If I am trying to create two objects of the class C. If default parameters are of the types, everything is OK.

int main()
{
C <Test <double> *, D1 > t1;
C <Test <double> *, D1 > t2(t1);
}

But if both parameters are of the different types

int main()
{
C <Test <double> *, D1 > t1;
C <Test <double> *, D2 > t2(t1);
}

Compiler stops on the line

if ( this != &source ) { //Code } //Error

with the following error:

Error   1   error C2446: '!=' : no conversion from 'const B<T,td> *' to 'B<T,td> *const 

My questions to the code:

1) Where (in which classes) and how to implement a copy constructor for different patameters of TD.

2) Where (in which classes) and how to implement operator = for different patameters of TD.

3) Where (in which classes) to implement the destructor.

Thanks you very much for your help.

Upvotes: 1

Views: 530

Answers (2)

Kit Fisto
Kit Fisto

Reputation: 4515

B<..., D1> and B<..., D2> are completely different classes, you cannot copy one into the other one. Perhaps you should write a templated copy function, if you really want to copy B<..., D1> objects into B<..l., D2> objects.

Upvotes: 1

kennytm
kennytm

Reputation: 523474

The problem is that you cannot compare pointers of different types. You should remove the this != &source line since objects of different types are supposingly not equal anyway, and implement another proper copy-constructor for the td == td2 case.

template <const TD td2>
B (const B<Item*, td2>& source)
{
    // code
}

B (const B& source)
{
    // code
}

Upvotes: 1

Related Questions