Why can't I override the default copy constructor and assignment operator with template versions in C++

前端 未结 2 1793
栀梦
栀梦 2020-12-11 18:07

I asked this question about overloading the copy constructor and assignment operator with template versions and considering the confusion involving around the question (sinc

相关标签:
2条回答
  • 2020-12-11 18:25
    template<typename T>
    BaseClass(const T& a_other) 
    

    First of all, this is not a copy-constructor. It is rather a templated constructor.

    The copy-constructor should be this:

    BaseClass(const BaseClass & a_other)
    

    Notice the difference?

    Note that the templated constructor doesn't define copy-constructor. The compiler will still generate a default copy-constructor for you, instead of instantiating the templated constructor.

    Same argument for copy-assignment.

    0 讨论(0)
  • 2020-12-11 18:49

    As mentioned in answers to your other question, the standard specifically disallows it.

    I'd guess that a rationale is that if a non-default for these constructors is necessary it would be because they need to deal with the specifics of the class in question. A 'generic' solution wouldn't make sense and might quietly hide potential problems.

    Some people might believe it's bad enough that there's already the 'generic' implicit versions of these functions, which silently does the wrong thing for many classes.

    The standardese disallowing template versino of these is here:

    From C++03 12.8 "Copying class objects"

    • (Para 1): A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (8.3.6)
    • (Para 9): A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&
    0 讨论(0)
提交回复
热议问题