mardi 28 décembre 2021

Why can't a copy constructor be templated? [duplicate]

I am doing a course C++ Fundamentals for Professionals on educative.io website, it mentioned the above statement added in the question,

I created a small c++ program to experiment the same -

#include<iostream>
using namespace std;

template<typename T1>
class MyTemplateClass
{
    
public:
    T1 data;

    MyTemplateClass()
    {
        cout << "in default const" << endl;
    }

    MyTemplateClass(const MyTemplateClass& other)
    {
        cout << "in default copy const - created automatically" << endl;
        this->data = other.data;
    }
    
    template<typename T>
    MyTemplateClass(const MyTemplateClass<T>& other)
    {
        cout << "in templated copy const" << endl;
        this->data = other.data;
    }
};


int main()
{
    cout << "hello world" << endl;
    MyTemplateClass<int> obj;
    MyTemplateClass<double> obj2(obj);
    MyTemplateClass<int> obj3(obj);

}

For obj3 it calls the default copy constructor which makes sense but for obj2 it calls the templated copy constructor, so I see a use for the constructor that if I have a class that takes T1 = double, we can created an object for it from an object of a class that takes T1 = int.

Does obj2 using template MyTemplateClass(const MyTemplateClass& other) - this function doesn't seem like a valid copy constructor according to the rules of a copy constructor defined in c++ but why is it such a case - since this seems like a valid use case?

Aucun commentaire:

Enregistrer un commentaire