//需要包含algorithm,vector,iostream
using namespace std;
template
inline F for_all(C v,F func) { return std::for_each(v.begin(),v.end(),func); }
//针对数组做特化,使for_all对容器和数组都有统一的接口 template inline F for_all(C (&v)[N],F f) { return std::for_each(&v[0],&v[0]+N,f); }
template void foo(T t) { cout< int main(int argc,char* argv[]) {
vector a;
int v[]={0,1,2,3,4};
for_all(a,foo); //不需要每次都要写begin(),end()方法,更紧凑
for_all(v,foo);
}
-----------------华丽的分割线---------------------
Comeau c++ 提供了在线的编译器,方便验证瞬间即失的想法
http://www.comeaucomputing.com/tryitout/
以下是编译上述代码的日志: Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 Copyright 1988-2008 Comeau Computing. All rights reserved. MODE:strict errors C++ C++0x_extensions In strict mode, with -tused, Compile succeeded (but remember, the Comeau online compiler does not link). Compiled with C++0x extensions enabled