Type `enum{}′ can′t be converted to tXPe `D<2>′ ("primes.cpp",L2/C25). Type `enum{}′ can′t be converted to txpe `D<3>′ ("primes.cpp",L2/C25). Type `enum{}′ can′t be converted to txpe `D<5>′ ("primes.cpp",L2/C25). Type `enum{}′ can′t be converted to txpe `D<7>′ ("primes.cpp",L2/C25). 如今,上面的代碼已經(jīng)不再是合法的C++程序了。以下是Erwin Unruh親手給出的修訂版,可以在今天符合標(biāo)準(zhǔn)的C++編譯器上進(jìn)行編譯:
// Prime number computation by Erwin Unruh
template <int i> struct D { D(void*); operator int(); };
template <int p, int i> struct is_prime { enum { prim = (p==2) (p%i) && is_prime<(i>2?p:0), i-1> :: prim }; };
template <int i> struct Prime_print { Prime_print<i-1> a; enum { prim = is_prime<i, i-1>::prim }; void f() { D<i> d = prim ? 1 : 0; a.f();} };
Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 17]' Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 13]' Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 11]' Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 7]' Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 5]' Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 3]' Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 2]' 這個(gè)例子展示了可以利用模板實(shí)例化機(jī)制于編譯期執(zhí)行一些計(jì)算。這種通過(guò)模板實(shí)例化而執(zhí)行的非凡的編譯期計(jì)算技術(shù)即被稱為模板元編程。
template <typename T> inline T sum_array(int Dim, T* a) { T result = T(); for (int i = 0; i < Dim; ++i) { result += a[i]; } return result; } 這當(dāng)然可行,但我們也可以利用模板元編程技術(shù)來(lái)解開循環(huán):
// sumarray2.h
// 原始模板 template <int Dim, typename T> class Sumarray { public: static T result(T* a) { return a[0] + Sumarray<Dim-1, T>::result(a+1); } };
// 作為終結(jié)準(zhǔn)則的局部特化版 template <typename T> class Sumarray<1, T> { public: static T result(T* a) { return a[0]; } }; 用法如下: