我有一个重载函数,如下所示:
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
被简化了(实际上它从数据库获取值)。
但我不知道该怎么做。
我最好的尝试是使用 boost::fusion::for_each 但我无法提供i
向下getColumn
.
另一种尝试是使用 boost::fusion 的迭代器,但这也不起作用:
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
}
我怎样才能打电话getColumn
对于每个类型Values...
具有正确的值i
并将结果保存在std::tuple
?
您需要将参数包的每个元素映射到包中的索引 - 这是“索引序列技巧”的典型用例:
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 进行现场演示。 http://coliru.stacked-crooked.com/a/1354af923ca0eef1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)