テンプレートを使ったポリシー(Policy)による処理の切り替え

コンパイル時に処理を切り替えたい場合に使用。Strategyパターンでは継承により処理を切り替えるが、こちらはテンプレートパラメーターで処理を切り替える。以下のサンプルコードは上述のLINK先のStrategyパターンのをもじって書いた。複数の特徴(戦略)をクラスに持たせる場合はこちらのほうが継承を使ったものよりもメンテの手間がはぶけてよい(継承を使うと全ケースの組み合わせを継承を使って書かねばならないので大変)

#include<string>
#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;

//ポリシークラスを呼ぶための箱
template<class Policy>
class MaxSearchStrategy
{
public :
    void Execute(const vector<int> & vec){Policy::Execute(vec);}
};

//ポリシークラス
class STLStrategy
{
public :
	static void Execute(const vector<int> & vec){
		vector<int>::const_iterator itr = max_element(vec.begin(),vec.end());
		cout << "===== STL Strategy =====\n";
		cout << "max: " << *itr << endl;
	}
};
class ForLoopStrategy
{
public :
	static void Execute(const vector<int> & vec){
		int result = INT_MIN;
		for(unsigned int i = 0; i < vec.size(); i++){
			result = vec.at(i) >= result ? vec.at(i):result;
		}
		cout << "===== For Loop Strategy =====\n";
		cout << "max: " << result << endl;
	}
};

//メイン関数
int main()
{
	//create sample data
	vector<int> data;
	data.push_back(2);
	data.push_back(5);
	data.push_back(4);
	data.push_back(1);
	data.push_back(6);
	data.push_back(3);

    //search max
    MaxSearchStrategy<STLStrategy>().Execute(data);
    MaxSearchStrategy<ForLoopStrategy>().Execute(data);

    return 0;
}

実行結果は

===== STL Strategy =====
max: 6
===== For Loop Strategy =====
max: 6