jeudi 18 février 2021

Add constructor to std::vector via friend

I'm not sure if my question is possible or if it might already have an answer somewhere but I'm not sure how to search for it.

I have made some sort of custom container (MyCollection). The most important thing is that is has begin() and end() function that return iterators. I want to convert a object of my custom container to an std::vector. What I can use is:

MyCollection<double> my_collection;
//... some operations
std::vector<double> std_collection(my_collection.begin(), my_collection.end());

But I would like to make it a bit more convenient for myself such that I could do:

MyCollection <double> my_collection;
//... some operations
std::vector<double> std_collection(my_collection);
std::vector<double> std_collection = my_collection;

Is there any way to add a constructor and assignment operator to an already existing class for which you can't change the class itself? I think maybe something with friend but I'm not to familiar with friend so I'm not sure if and how it could be used here. Just a no it can't be done is also an super acceptable answer.

For those of you suggesting to make a separate class which inherits and extends std::vector that is not the way I would like to go.

And I'm forced to stick to c++11 for now so I would especially appreciate solutions for that but if it can be done for younger standards I would still be interested

Aucun commentaire:

Enregistrer un commentaire