在一个模板元程序中要计算任意的循环
首先必须再用公式表示递归
用一个模板元程序来实现
//: C05:Power.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#include <iostream>
using namespace std;
template<int N, int P> struct Power {
enum { val = N * Power<N, P-1>::val };
};
template<int N> struct Power<N, 0> {
enum { val = 1 };
};
int main() {
cout << Power<2, 5>::val << endl; // 32
getchar();
} ///:~
输出
32
N仍是一个自由模板参数
需要用一个半特化来作为终止条件
//: C05:Accumulate.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Passes a "function" as a parameter at compile time.
#include <iostream>
using namespace std;
// Accumulates the results of F(0)..F(n)
template<int n, template<int> class F> struct Accumulate {
enum { val = Accumulate<n-1, F>::val + F<n>::val };
};
// The stopping criterion (returns the value F(0))
template<template<int> class F> struct Accumulate<0, F> {
enum { val = F<0>::val };
};
// Various "functions":
template<int n> struct Identity {
enum { val = n };
};
template<int n> struct Square {
enum { val = n*n };
};
template<int n> struct Cube {
enum { val = n*n*n };
};
int main() {
cout << Accumulate<4, Identity>::val << endl; // 10
cout << Accumulate<4, Square>::val << endl; // 30
cout << Accumulate<4, Cube>::val << endl; // 100
getchar();
} ///:~
输出
10
30
100
基本的Accumulate模板试图技术F(n)+F(n-1)...F(0)的和
终止递归是通过一个 返回 F(0)的半特化来实现的
参数F本身是一个模板
Accumulate的第1个实例化计算是求和 4+3+2+1+0
第2个计算数字的平方和 16+9+4+1+0
最后计算立方和 64+27+8+1+0