Question:
Assume a function
void doFoo(const std::vector<std::reference_wrapper<DataT> >& data);
where DataT
is some type holding some data. I used std::vector
just as the typical example of a container class.
What would you say is the most elegant way to call the above function with a std::vector<DataT>
?
Background:
Inside the function doFoo(...)
I don't want to take ownership of the data. Thus, I don't want to use std::shared_ptr
or std::unique_ptr
. As I understand it the correct way is to use a reference. If I just use a reference to a std::vector<DataT>
I might have to copy several DataT
to create the vector for the function call in case I did not construct the data directly in a std::vector<DataT>
. Thus, a std::vector<std::reference_wrapper<DataT> >
seems to be the best solution.
If I only have a single DataT
object (let's call it data1
) I can easily put it into the function by calling doFoo({data1})
and the correct vector will be constructed implicitly. But if I already have a std::vector<DataT> dataVec
and try to call doFoo(dataVec)
it is not implicitly converted to a std::vector<std::reference_wrapper<DataT> >
, because the types are completely unrelated.
Possible Solutions:
- Create a
std::vector<std::reference_wrapper<DataT> >
before calling the function and fill it with the references to all elements indataVec
.
Disadvantage: I have to do this repacking for each function call. - Overload
doFoo(...)
to take astd::vector<DataT>
and do the repacking there.
Disadvantage: If I use this concept in many places it creates quite some boilerplate code. Also, to me it seems a bit redundant and maybe even confusing to have that extra function call. - Enable some implicit conversion from
std::vector<DataT>
to astd::vector<std::reference_wrapper<DataT> >
. But I don't know whether this is possible at all, and if it might have some bad consequences. If this or something similar is possible and safe I would prefer this solution.