How to write Template class copy constructor

天大地大妈咪最大 提交于 2020-01-12 20:57:33

问题


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:
};

回答1:


Assuming _TyV is a value type:

Vertex( Vertex const& src )
    : m_Label( src.m_Label )
{}

Aren't those names within class instances reserved by the implementation, by the way?

The C++ standard reserves a set of names for use by C++ implementation and standard libraries [C++ standard 17.6.3.3 - Reserved names]. Those include but are not limited to:

  • Names containing a double underscore.
  • Names that begin with an underscore followed by an uppercase letter.
  • Names that begin with an underscore at the global namespace.



回答2:


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.




回答3:


template <typename T>
class Vertex {
public:

    //this is copy-constructor
    Vertex(const Vertex<T> &other) 
          : m_Color(other.m_Color),m_Label(other.m_Label)
    {
      //..
    }
    //..
};

But I don't think you need to explicitly define the copy-constructor, unless the class have pointer member data and you want to make deep-copy of the objects. If you don't have pointer member data, then the default copy-constructor generated by the compiler would be enough.



来源:https://stackoverflow.com/questions/7638296/how-to-write-template-class-copy-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!