C++拾遺--模板元編程

                          C++拾遺--模板元編程

前言

    模板元是用於遞歸加速的,把運行期的函數調用變到編譯期進行代碼展開,類似於內聯函數。下面看一個實例:斐波那契數列第n項求解。

模板元編程

#include <iostream>
#include <ctime>
using namespace std;
//遞歸法
int fib(int n)
{
	if (n < 0)
		return 0;
	if (n == 1 || n == 2)
		return 1;
	return fib(n - 1) + fib(n - 2);
}
//模板元
template<int N>
struct Data
{
	enum{ res = Data<N-1>::res + Data<N-2>::res };
};
template<>
struct Data<1>
{
	enum{ res = 1 };
};
template<>
struct Data<2>
{
	enum{ res = 1 };
};
int main()
{
	cout << "******模板元編程***by David***" << endl;
	time_t start, end;
	start = clock();
	cout << fib(40) << endl;
	end = clock();
	cout << "遞歸法耗時" << end - start << "ms" << endl;
	start = clock();
	cout << Data<40>::res << endl;
	end = clock();
	cout << "模板元法耗時" << end - start << "ms" << endl;
	cin.get();
	return 0;
}
運行



總結:

遞歸法耗時較久。模板元法的運行時間是有問題的,在VS上把鼠標移到Data<40>::res時就可以看到結果。




本專欄目錄

所有內容的目錄



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章