我有以下功能:
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) )
我看到的其他问题涉及解压给定的元组,而不是以这种方式构建元组。
使用 C++14 实现您正在寻找的内容变得非常简单integer_sequence http://en.cppreference.com/w/cpp/utility/integer_sequence。如果你没有可用的,这是一个 C++11 实现 https://gitorious.org/redistd/integer_seq/source/24293c100405bf3982732f53897b4beb962a9086:integer_seq.h写于乔纳森·韦克利 https://stackoverflow.com/users/981959/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>>();
现场演示 http://coliru.stacked-crooked.com/a/5230fc856df021da
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)