3

我正在寻找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>’

所以似乎递归情况不被识别,但为什么呢?

4

2 回答 2

3

递归模板很少需要;包扩展通常更清晰、更简单。在这种情况下,只需使用tuple_element

template<typename T, size_t... indexes>
class Projection{
public:
    using Tuple = std::tuple<typename std::tuple_element<indexes, T>::type...>;
};

同上project

template<size_t... indexes, typename T>
auto project(const T &t) -> typename Projection<T, indexes...>::Tuple {
    return typename Projection<T, indexes...>::Tuple(std::get<indexes>(t)...);
}
于 2014-05-12T15:12:21.970 回答
1

您可以使用以下内容:

#define Return(ret) decltype(ret) { return ret; }

template<std::size_t... Is, typename T>
auto project(const T& t) -> Return(std::make_tuple(std::get<Is>(t)...))
于 2014-05-12T15:22:29.440 回答