我有以下功能:
template<class T>
T Check(int index);
如何编写一个函数CheckTuple
,在给定元组类型的情况下,通过调用Check
来填充元组?
例如:
CheckTuple< std::tuple<int, float, std::string> >()
将返回以下元组:
std::make_tuple( Check<int>(1), Check<float>(2), Check<std::string>(3) )
我看到的其他问题涉及解包给定元组,而不是以这种方式构建一个元素。
答案 0 :(得分:4)
使用C ++ 14 integer_sequence
实现您正在寻找的内容变得非常简单。如果您没有here's a C++11 implementation由Jonathan Wakely撰写,
template<typename Tuple, int... I>
Tuple CallCheck(std::integer_sequence<int, I...>)
{
return std::make_tuple(Check<typename std::tuple_element<I, Tuple>::type>(I)...);
}
template<typename Tuple>
Tuple CheckTuple()
{
return CallCheck<Tuple>(std::make_integer_sequence<int, std::tuple_size<Tuple>::value>());
}
// Use it as
auto tup = CheckTuple<std::tuple<int, float, std::string>>();
答案 1 :(得分:2)
这是我的工作测试实现。 (或许有人知道如何在简洁性方面对其进行改进。我能以某种方式摆脱TupleInfo吗?)
#include <typeinfo>
#include <tuple>
#include <iostream>
template<class T>
T Check(int i) {
std::cout << "getting a " << typeid(T).name() << " at position " << i << std::endl;
return T();
}
template<typename Signature>
struct TupleInfo;
template<class T, class... Args>
struct TupleInfo< std::tuple<T, Args...> > {
using Head = T;
using Tail = std::tuple<Args...>;
};
template<int N, class Tuple>
struct TupleChecker {
static Tuple CheckTuple() {
auto t = std::make_tuple(Check<typename TupleInfo<Tuple>::Head>(N));
return std::tuple_cat(t, TupleChecker<N+1, typename TupleInfo<Tuple>::Tail >::CheckTuple());
}
};
template<int N>
struct TupleChecker<N, std::tuple<> > {
static std::tuple<> CheckTuple() {
return std::tuple<>();
}
};
template<class Tuple>
Tuple CheckTuple() {
return TupleChecker<1, Tuple>::CheckTuple();
}
int main() {
std::tuple<> t0 = CheckTuple<std::tuple<> >();
std::tuple<int> t1 = CheckTuple<std::tuple<int> >();
std::tuple<int, float, std::string> t2 = CheckTuple<std::tuple<int, float, std::string> >();
return 0;
}