I have this vector:
std::vector<T*> foo;
I have a function with the following signature (I can not alter it):
void bar(std::vector<T> const&);
How Can I pass foo to that function with minimum changes?
My current approach is:
std::vector<T> another_bar(bar.size());
std::transform(std::begin(bar),std::end(bar),std::begin(another_bar),[](T* item){return *T;});
I think there is a lot of unnecessary copying is happening here.
EDIT:
T is not a templated parameter. It is a specified type.
Whereas you need to to some copies, you may avoid to construct default value and then create copy by direct copy construct:
std::vector<T> another_bar;
another_bar.reserve(bar.size());
std::transform(std::begin(bar), std::end(bar),
std::back_inserter(another_bar),[](T* item){return *item;});
Your approach is as correct as possible. You have to do a lot of copying. Another problem is that it will also "slice" if you have any classes derived from T. Sometimes you have two dissimilar programs and it is unavoidable, but more likely you should reevaluate the design of either the caller or the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With