1 template<typename AnyType> 2 void TestSwapNData(AnyType* a,AnyType* b,int n) 3 { 4 AnyType Temp; 5 for (int i = 0; i < n; i++) 6 { 7 Temp = a[i]; 8 a[i] = b[i]; 9 b[i] = Temp; 10 } 11 }
代码中,typename 可以替换成关键字class,两个关键字的效果是一样的
示例使用
1 int main() 2 { 3 char buf1[10] = {0}; 4 char buf2[10] = {0}; 5 6 memcpy(buf1,"123456789",sizeof("123456789") ); 7 memcpy(buf2,"abcdefghi",sizeof("abcdefghi") ); 8 std::cout<<buf1<<std::endl<<buf2<<std::endl; 9 10 TestSwapNData(buf1,buf2,5); 11 std::cout<<buf1<<std::endl<<buf2<<std::endl; 12 13 return 0; 14 }
运行结果显示:
PS:前两行是交换之前的数据,后两行是交换之后的数据