template constructor one parameter const and not const

144 Views Asked by At

I try to use template constructor with one parameter. I try 2 cases const parameter and non-const.

class Foo1
{
public:
   Foo1() {}
   template <typename T>
   Foo1(const T& f) 
   {
       cout<<"Foo1"<<endl;
    }
};
class Foo2
{
public:
   Foo2() {}
   template <typename T>
   Foo2( T& f) 
   {
       cout<<"Foo2"<<endl;

    }
};

int main()
{
    Foo1 f1;
    Foo1 f11(f1);
    Foo2 f2;
    Foo2 f21(f2);
}

The output is: Foo2

so default copy constructor is generated for Foo1 and not for Foo2.

when I change main function to:

int main()
{
    const Foo1 f1;
    Foo1 f11(f1);
    const Foo2 f2;
    Foo2 f21(f2);
}

Output is empty:

so both copy constructed are geerated. Why is that behaviour?

1

There are 1 best solutions below

0
On BEST ANSWER

so default copy constructor is generated for Foo1 and not for Foo2.

Wrong.

Both copy constructors are generated, but

template <typename T> Foo2( T& f) // with T = Foo2

is a better (exact) match than copy constructor, as you pass a non const Foo2.