Saturday, 16 September 2017

c++ - Inheriting copy and move constructors of base class using "using" keyword

I want to inherit copy constructor of the base class using using keyword:



#include 


struct A
{
A() = default;

A(const A &) { std::cerr << __PRETTY_FUNCTION__ << std::endl; }
A( A &&) { std::cerr << __PRETTY_FUNCTION__ << std::endl; }

A& operator=(const A &) { std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this; }
A& operator=( A &&) { std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this; }
};


struct B : A
{
using A::A;
using A::operator=;

B& operator=(const B &) { std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this; }
B& operator=( B &&) { std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this; }
};


int main()
{
A a;
B b;
b = a; // OK
B b1( a ); // compile error
B b2(std::move(a)); // compile error
return 0;
}



Inheriting assignment operator using using keyword works OK, but inheriting copy and move constructors causes a compilation error: an inherited constructor is not a candidate for initialization from an expression of the same or derived type.



http://coliru.stacked-crooked.com/a/fe84b429c391c894:



main.cpp:16:14: note:   an inherited constructor is not a candidate for initialization from an expression of the same or derived type
main.cpp:8:5: note: candidate: A::A(A&&)
A( A &&) { std::cerr << __PRETTY_FUNCTION__ << std::endl; }
^
main.cpp:16:14: note: inherited here

using A::A;


Why can I inherit assignment operator but cannot inherit copy constructor? What is a difference? I could understand if I couldn't inherit assignment operators too. But inheriting assignment operators in contrary is considered OK. That is a little strange for me.



The story



What I want is similar to what is asked in this question: I want to just add new methods to existing class without modifying it (it's a class from another library).



http://coliru.stacked-crooked.com/a/149a6194717cd465:




#include 

struct A // not my class
{
};

struct B : A
{
using A::A;

using A::operator=;

void foo() { std::cerr << "fuu" << std::endl; }
};

A NotMyFunc()
{
return {};
}


int main()
{
B b(NotMyFunc());
b.foo();
return 0;
}


But I don't want to reimplement copy and move constructors.

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...