C++11:模板元编程入门

发布时间 2023-03-25 07:25:59作者: karinto

1、实现斐波那契数列和最大公约数在编译期的求值

#include <iostream>

using namespace std;

/*阶乘*/
template<int N>
struct Fac {
	const static int value = N * Fac<N - 1>::value;
};

template<>
struct Fac<0> {
	const static int value = 1;
};

/*斐波那契数列*/
template<int N>
struct Fib {
	const static int value = Fib<N - 1>::value + Fib<N - 2>::value;
};

template<>
struct Fib<1> {
	const static int value = 1;
};

template<>
struct Fib<2> {
	const static int value = 1;
};

/*最大公约数, 递归*/
template<int a, int b>
struct Gcd {
	const static int value = Gcd<b, a%b>::value;
};

template<int a> //传递双参数, 这里只模板特化了int b
struct Gcd<a, 0> {
	const static int value = a;
};

int main() {
	Fac<3>::value; //编译期 = 6
	Fib<7>::value; //编译期 = 13
	Fib<100>::value; //int上溢, 复杂度O(N)
	Gcd<24, 36>::value; //12
}

 

2、