Copy constructor of template class

后端 未结 2 2104
孤独总比滥情好
孤独总比滥情好 2020-11-28 09:46

I read that template copy-con is never default copy onstructor, and template assignment-op is never a copy assignment operator.

I couldn\'t understand why this res

相关标签:
2条回答
  • 2020-11-28 09:51

    I can't comment on why this is how it is, but here's how you write a copy constructor and assignment operator for a class template:

        template <class T>
        class A
        {
          public:
            A(const A &){}
            A & operator=(const A& a){return *this;}
        };
    

    and that's it.
    The trick here is that even though A is a template, when you refer to it inside the class as A (such as in the function signatures) it is treated as the full type A<T>.

    0 讨论(0)
  • 2020-11-28 09:56

    There are strict rules what constitutes a copy constructor (cf. C++11, 12.8):

    • It is not a template.

    • For a class T, its first argument must have type T & or T const & or T volatile & or T const volatile &.

    • If it has more than one argument, the further arguments must have default values.

    If you do not declare a copy constructor, a copy constructor of the form T::T(T const &) is implicitly declared for you. (It may or may not actually be defined, and if it is defined it may be defined as deleted.)

    (The usual overload resolution rules imply that you can have at most four copy constructors, one for each CV-qualification.)

    There are analogous rules for move constructors, with && in place of &.

    0 讨论(0)
提交回复
热议问题