引用和模板

来源:互联网 发布:ap网络课程百度云 编辑:程序博客网 时间:2024/05/16 04:52
引用在C++中主要用于函数参数传递。在template中有很有意义。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// function that prints the passed argument
void print (int elem)
{
    cout << elem << ' ';
}
void print1 (int &elem)
{
//    cout << elem << ' ';
    elem *= 2;
}
void print2 (int elem)
{
//    cout << elem << ' ';
    elem *= 2;
}

int main()
{
    vector<int> coll;

    // insert elements from 1 to 9
    for (int i=1; i<=9; ++i) {
        coll.push_back(i);
    }

    // print all elements
    for_each (coll.begin(), coll.end(),    // range
              print);                      // operation
    cout << endl << "start print1" <<endl;
    for_each (coll.begin(), coll.end(),    // range
              print1);                      // operation
    for_each (coll.begin(), coll.end(),    // range
              print);                      // operation
    cout << endl << "end for  print1" <<endl;
    cout << endl << "start print2" <<endl;
    for_each (coll.begin(), coll.end(),    // range
              print2);                      // operation
    for_each (coll.begin(), coll.end(),    // range
              print);                      // operation
    cout << endl << "end for  print2" <<endl;
    cout << endl << "start print1" <<endl;
    for_each (coll.begin(), coll.end(),    // range
              print1);                      // operation
    for_each (coll.begin(), coll.end(),    // range
              print);                      // operation
    cout << endl <<"end for  print1" <<endl;
    cout << endl;
}
得到结果:
1 2 3 4 5 6 7 8 9
start print1
2 4 6 8 10 12 14 16 18
end for  print1

start print2
2 4 6 8 10 12 14 16 18
end for  print2

start print1
4 8 12 16 20 24 28 32 36
end for  print1
在此时,不需要改变template,只须改变被传递的函数定义,大大提高了template的重用机会

原创粉丝点击