I have a overloaded function which looks like:
template<typename T>
T getColumn(size_t i);
template<>
std::string getColumn<std::string>(size_t i) {
if(i == 0)
return "first";
else
return "other";
}
template<>
int getColumn<int>(size_t i) {
return i*10;
}
// ...
Now I want to implement the function
template<typename... Values>
std::tuple<Values...> getColumns();
Which creates a tuple (for the return value) and calls getColumn
for every element of the tuple (saving the return value in that element), where i
is the position of the element. The code which generates the return value of getColumn
is simplified (in reality it gets the value from a database).
But I have no idea how to do that.
My best try was with boost::fusion::for_each but I wasn't able to hand i
down to getColumn
.
Another try was with the iterators from boost::fusion, but that also didn't work:
namespace fusion = boost::fusion;
tuple<Values...> t;
auto it = fusion::begin(t);
while(it != fusion::end(t)) {
getColumn(distance(fusion::begin(t), it), fusion::deref(it));
it = fusion::next(it); // error: assignment not allowed
}
How can I call getColumn
for every Type from Values...
with the correct value for i
and save the results in a std::tuple
?
You need to map each element of a parameter pack to its index within the pack - this is the typical use case for the "index sequence trick":
Live demo at Coliru.