填充std ::元组 [英] Filling a std::tuple

查看:231
本文介绍了填充std ::元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重载的函数,它看起来像:

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;
}

// ...

以实现函数

template<typename... Values>
std::tuple<Values...> getColumns();

这将创建一个元组(对于返回值)并调用 getColumn 为元组的每个元素(保存元素中的返回值),其中 i 是元素的位置。生成 getColumn 的返回值的代码被简化(实际上它从数据库获取值)。

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).

但我不知道该怎么做。

我最好的尝试是boost :: fusion :: for_each,但我不能手<$ c $

My best try was with boost::fusion::for_each but I wasn't able to hand i down to getColumn.

另一个尝试是使用boost的迭代器:: fusion,但这也不起作用:

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
}

如何调用 正确的值为> 将结果保存在 std :: tuple

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

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)>());
}

在Coliru现场演示

这篇关于填充std ::元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆