Filling a std::tuple

馋奶兔 提交于 2019-12-24 04:01:11

问题


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?


回答1:


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":

template <int... I> struct index_sequence {};
template <int N, int... I>
struct make_index_sequence : make_index_sequence<N-1,N-1,I...> {};
template <int... I>
struct make_index_sequence<0, I...> : index_sequence<I...> {};

template<typename... Values, int... I>
auto getColumns(index_sequence<I...>) ->
  decltype(std::make_tuple(getColumn<Values>(I)...)) {
    return std::make_tuple(getColumn<Values>(I)...);
}

template<typename... Values>
auto getColumns() ->
  decltype(getColumns<Values...>(make_index_sequence<sizeof...(Values)>())) {
    return getColumns<Values...>(make_index_sequence<sizeof...(Values)>());
}

Live demo at Coliru.




回答2:


Maybe with auto:

template<typename... Values>
auto getColumns() -> decltype(std::make_tuple(getColumns<Values>()...))
{
    return std::make_tuple(getColumns<Values>()...);
}

In C++14, you'll be able to omit the -> decltype... part, since it will be deduced from the function body.



来源:https://stackoverflow.com/questions/20816745/filling-a-stdtuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!