为了使诸如 for_each 之类的 c++ STL 算法可以使用更多参数,重载在这里起作用:
template<typename II1, typename II2, typename F>
F for_each( II1 _ii1, II1 ii1_, II2 _ii2, F f )
{
while ( _ii1 != ii1_ )
{ f( *_ii1++, *_ii2++ ); }
return f;
}
template<typename II1, typename II2, typename II3, typename F>
F for_each( II1 _ii1, II1 ii1_, II2 _ii2, II3 _ii3, F f )
{
while ( _ii1 != ii1_ )
{ f( *_ii1++, *_ii2++, *_ii3++ ); }
return f;
}
template<typename II1, typename II2, typename II3, typename II4, typename F>
F for_each( II1 _ii1, II1 ii1_, II2 _ii2, II3 _ii3, II4 _ii4, F f )
{
while ( _ii1 != ii1_ )
{ f( *_ii1++, *_ii2++, *_ii3++, *_ii4++ ); }
return f;
}
但是有没有办法使用可变参数模板来实现这种功能?
我只能让它这样工作
void increase(){}
template< typename II1, typename ... IIn >
void increase( II1& _ii1, IIn& ... _iin )
{
++_ii1;
increase( _iin... );
}
template<typename F, typename II1, typename ... IIn >
F for_each( F f, II1 _ii1, II1 ii1_, IIn ... _iin )
{
while ( _ii1 != ii1_ )
{
f( *_ii1, *_iin ... );
increase( _ii1, _iin... );
}
return f;
}
#include <iostream>
int main()
{
int A[10];
int B[10];
int i = 0;
for_each( [&i]( int & v ) { v = i++; }, A, A+10 );
for_each( []( int a, int & b ) { b = a; }, A, A+10, B );
for ( int i = 0; i != 10; ++i )
{ std::cout << A[i] << "\t" << B[i] << "\n"; }
return 0;
}
这是非常丑陋的。
编辑:(2012 年 6 月 22 日星期五 21:12:28 CEST)
为此,我必须编写如下代码:
for_each( function, begin1, end1, begin2, begin3 );
虽然首选 stl 的方式:
for_each( begin1, end1, begin2, begin3, function );
编辑:(2012 年 6 月 22 日星期五 23:55:27 CEST)
在@Hurkyl 的帮助下,现在我可以使用这些代码:
namespace for_each_impl_private
{
template< typename F, typename InputIterator1, typename ... InputIteratorn >
F _for_each( F f, InputIterator1 begin1, InputIterator1 end1, InputIteratorn ... beginn )
{
while ( begin1 != end1 )
f( *begin1++, *beginn++... );
return f;
}
struct dummy {};
template< typename S, typename ... T >
void rotate_then_impl( S s, T ... t )
{
rotate_then_impl( t..., s );
}
template< typename S, typename ... T>
void rotate_then_impl( S s, dummy, T ... t )
{
_for_each( s, t... );
}
}//namespace for_each_impl_private
template< typename ... T >
void for_each( T ... t )
{
static_assert( sizeof ... ( t ) > 2, "for_each requires at least 3 arguments" );
for_each_impl_private::rotate_then_impl( t..., for_each_impl_private::dummy() );
}
#include <iostream>
int main()
{
int A[10];
int B[10];
int i = 0;
for_each( A, A + 10, [&i]( int & v ) { v = i++; } );
for_each( A, A + 10, B, []( int a, int & b ) { b = a; } );
for_each( A, A + 10, B, []( int a, int b ) { std::cout << a << "\t" << b << "\n"; } );
return 0;
}