我正在寻找std::tuple
. 即,该函数接收一个整数列表作为模板参数,并返回一个仅在这些索引处具有值的元组。
例如,假设我有一个 tuple tuple<int,String,char,float> t
,那么调用 toproject<1,3>(t)
会产生一个 type 的元组tuple<String,float>
。
当然,关键似乎是递归模板。但是,我无法让它工作。我尝试通过声明一个结构来计算投影操作的返回类型。即使这样也失败了。这是我尝试过的:
template<typename T, size_t... indexes>
class Projection{
};
// Specialization for no index => Empty tuple
template<>
template<typename... T>
class Projection<std::tuple<T...>>{
typedef std::tuple<T...> InputTuple;
typedef std::tuple<> Tuple;
};
// Specialization for one or more parameters
template<size_t Index1, size_t... others>
template<typename... T>
class Projection<std::tuple<T...>,Index1,others...>{
typedef std::tuple<T...> InputTuple;
// The type of a projection with one column less
typedef Projection<std::tuple<T...>,others...> TupleMinusOne;
// The result type is the catenation of TupleMinusOne plus the column projected in this step
typedef decltype(std::tuple_cat(std::make_tuple(std::get<Index1>(InputTuple())),typename TupleMinusOne::Tuple())) Tuple;
};
这编译。具有空元组的基本情况也适用,即:
Projection<std::tuple<int,std::string>>::Tuple t;
结果t
是一个空元组。但是,递归案例无法编译:
Projection<std::tuple<int,std::string>,1>::Tuple t;
我收到以下错误:
Test.cpp:79:1: error: ‘Tuple’ is not a member of ‘Projection<std::tuple<int, float>, 1ul>’
所以似乎递归情况不被识别,但为什么呢?