看過了funciton object中的部分內容,感覺這些技術、 概念等真的需要慢慢體會,才能感受到它的博大精深。
看下面的這個例子:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void printInt (int elem)
{
cout << elem << ' ' ;
}
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(),printInt);
cout << endl;
}
對于這個例子,for_each()的第三個參數,調用了printInt這個函數。在看下面的例子:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//simple function object that prints the passed argument
class PrintInt {
public:
void operator() (int elem) const {
cout << elem << ' ';
}
};
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(), PrintInt());
cout << endl;
}
在這個例子中,for_each()的第三個參數就是函數對象。
那么這到底有什么區別呢?也許從上面的代碼中還看不出,但是,請繼續看下面的例子:
//對每一個element加10;
void add10 (int& elem)
{
elem += 10;
}
void fl()
{
vector<int> coll;
...
for_each (coll.begin(), coll.end(), add10);
}
這樣看起來似乎很好,但是,如果突然要求變了,要求對每一個element改成加9;那么,可能想到的辦法是改寫函數
void add9 (int& elem)
{
elem +=9;
}
哦,那么要求又改成+8、+7…… -3等等,總不至于對于每一個都重新寫一個函數吧?雖然可行,但是違背
范型變成的思想。也許有新的辦法:
template <int theValue>
void add (int& elem)
{
elem += theValue;
}
void f1()
{
vector<int> coll;
...
for_each (coll.begin() , coll.end(), //range
add<10>); //operation
}
但是,如果連類型(int)都變了(如改成float),那該怎么實現呢?哦,用一般的函數應該不能實現了吧?
但是如果用function object思想,就可以實現,看下面的代碼:
template <class T>
class AddValue {
private:
T theValue;
public:
AddValue(T v) : theValue(v) {
}
void operator() (T& elem) const {
elem += theValue;
}
};
現在這個類就可以實現多個類型的相加形式了。
因此可以總結在用函數對象時,可以更加滿足了STL的范型編程思想。