作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在不使用典型的 index_sequence & tuple 技巧的情况下将参数包拆分为第一个 N - 1 和第 N 个参数,但似乎无法解决它,但我很确定它应该可行吗? (通过递归获得最后一项很容易)。
要调用的最终函数看起来像
void Fun( Foo a, Bar b );
template< class... T >
Foo CalcFoo( T... args );
//get the last item of the pack
template< class T >
T split_last( T t ){ return t; }
template< class... T >
T split_last( T, T... t ){ return split_last( t... ); }
//helper
template< class... T, size_t... Indices >
Foo CalcFoo( const std::tuple< T... >& args, index_sequence< Indices... > )
{
return CalcFoo( std::get< Indices >( args )... );
}
//split and call
template< class... T >
void MoreFun( T... args )
{
//make a tuple containing all, then get n -1 items out of it
const auto tup = std::make_tuple< T... >( args... );
Fun( CalcFoo( tup, make_index_sequence< sizeof...( T ) - 1 >() ),
split_last( args... ) );
}
CalcFoo
内联直到调用
Fun
.换句话说:元组完全消失了。所以无论如何我可能会坚持这个实现,因为它很清楚。
最佳答案
好吧,让我们发挥创意。我确定有一种更“标准”的方法可以做到这一点,但我有点喜欢这个解决方案;)
http://coliru.stacked-crooked.com/a/25a3fa276e56cd94
核心思想是递归地旋转参数,直到我们可以分离出(以前的)最后一个参数。
template <size_t N>
struct MoreFunHelper
{
template <class Head, class... Tail>
static void RotateLeft(Head head, Tail... tail)
{
MoreFunHelper<N - 1>::RotateLeft(tail..., head);
}
};
template <>
struct MoreFunHelper<0>
{
template <class Head, class... Tail>
static void RotateLeft(Head head, Tail... tail)
{
Fun(CalcFoo(tail...), head);
}
};
template< class... T >
void MoreFun(T... args)
{
MoreFunHelper<sizeof...(T) - 1>::RotateLeft(args...);
}
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4
CalcFoo
和
Fun
.
关于c++11 - 将参数包拆分为 0 ... N-1 和第 N 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25685810/
我是一名优秀的程序员,十分优秀!