mardi 30 janvier 2018

How to determine if the type being passed in copy constructor is same as the type in member variable

I am trying to come up with a rough sketch of a basic shared pointer. In the copy constructor I would like to ensure that the passed object is of the same type as the one present in its member variable. This is the rookie code I have so far.

template <typename t>
class myshared
{
    public:
    myshared(t* ptr) : obj(ptr)
    {
        counter++;
        std::cout << "Regular constructor called"<< std::to_string(counter+1) << std::endl;
    }

    //Copy constrcutor
    myshared(const myshared<t>& obj)
    {
         this->obj = obj.obj;
        std::cout << "Copy constrcutor called" << std::to_string(counter+1)<< std::endl;
    }

    t* operator->()
    {
        return obj;
    }

    ~myshared()
    {
        counter--;
        std::cout << "destructor called " << std::to_string(counter) << std::endl;

    }
    private:
    int counter=0;
    t* obj;
};

int main() 
{
    myshared<foo> first(new foo());
    myshared<foo> sec(first);
    sec->x =12;
}

Now my question is regarding the copy constructor

myshared(const myshared<t>& obj)
{
}

The above I believe would accept any template type of myshared. I would like it to only accept the type similar to its member variable t* objtype. How can I accomplish that ?

Aucun commentaire:

Enregistrer un commentaire