引用和模板

引用在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的重用机会

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值