Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Template class copy constructor

How to write copy constructor for a template class. So that if the template parameter is another user defined class it's copy constructor is also get called.

Following is my class

template <typename _TyV>
class Vertex {
public:
    Vertex(_TyV in) :   m_Label(in){ }
    ~Vertex() { }
    bool operator < ( const Vertex & right) const {
        return m_Label < right.m_Label;
    }

    bool operator == ( const Vertex & right ) const {
        return m_Label == right.m_Label;
    }

    friend std::ostream& operator << (std::ostream& os, const Vertex& vertex) {
        return os << vertex.m_Label;    
    }

    _TyV getLabel() { return m_Label;}
private:
    _TyV m_Label;
public:
    VertexColor m_Color;
protected:
};
like image 395
Avinash Avatar asked Oct 03 '11 17:10

Avinash


People also ask

Can a copy constructor be a template?

The copy constructor lets you create a new object from an existing one by initialization. A copy constructor of a class A is a non-template constructor in which the first parameter is of type A& , const A& , volatile A& , or const volatile A& , and the rest of its parameters (if there are any) have default values.

What is the syntax of template class?

1. What is the syntax of class template? Explanation: Syntax involves template keyword followed by list of parameters in angular brackets and then class declaration.

What is the copy constructor of a class?

A copy constructor is a member function that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor.


1 Answers

Either a) not at all, just rely on the compiler-provided default; or b) by just invoking the copy constructor of the member:

template <typename T> struct Foo
{
  T var;
  Foo(const Foo & rhs) : var(rhs.var) { }
};

The point is of course that the compiler-provided default copy constructor does precisely the same thing: it invokes the copy constructor of each member one by one. So for a class that's composed of clever member objects, the default copy constructor should be the best possible.

like image 121
Kerrek SB Avatar answered Sep 18 '22 04:09

Kerrek SB