Home > Mobile >  template constructor selected instead of copy constructor C
template constructor selected instead of copy constructor C

Time:01-18

Let following program:

#include <variant>

struct A{
    A(){}
    ~A(){}
   A(const A&){}
   A& operator = (const A&) { return *this;}
   A(A&&){}
   A& operator = (A&& ) { return *this; }

   using var = std::variant<int, float>;

   var v;

   template<typename T>
   A(T&& t): v(std::forward<T>(t)){}

};

struct B
{
   A m_a;
   B( A a) : m_a(a) //calls template constructor instead of copy!
   {}
};

Live example: godbold example

Q: Why template generic constructor chosen instead of copy (or move) constructor?

Edit : I think that, this is not duplicate of Why isn't this templated move constructor being called?

Because that issue asks why templated constructor NOT called?. That issue problem is - NOT called templated constructor.

I'm asking why templated constructor IS calling?. My problem is -- on the contrary, calling templated constructor. :)

CodePudding user response:

It's just a better match. The template will instantiate a ctor that looks like: A(T& t): v(t)){}

either pass as const& https://godbolt.org/z/78bdzczE5

or create better matching ctor https://godbolt.org/z/b8WvjW38T

  • Related