导言

1994年,C++标准委员会在圣迭哥举行的一次会议期间Erwin Unruh展示了一段可以产生质数的代码。这段代码的特别之处在于质数产生于编译期而非运行期,在编译器产生的一系列错误信息中间夹杂着从2到某个设定值之间的所有质数: 

1 // Prime number computation by Erwin Unruh

2 template <int i> struct D { D(void*); operator int(); };

4 template <int p, int i> struct is_prime {

5     enum { prim = (p%i) && is_prime<(i > 2 ? p : 0), i -1> :: prim };

6 };

8 template < int i > struct Prime_print {

9     Prime_print<i-1> a;

10     enum { prim = is_prime<i, i-1>::prim };

11     void f() { D<i> d = prim; }

12 };

13 

14 struct is_prime<0,0> { enum {prim=1}; };

15 struct is_prime<0,1> { enum {prim=1}; };

16 struct Prime_print<2> { enum {prim = 1}; void f() { D<2> d = prim; } };

17 #ifndef LAST

18 #define LAST 10

19 #endif

20 main () {

21     Prime_print<LAST> a;

22 }

复制代码

类模板D只有一个参数为void*的构造器,而只有0才能被合法转换为void*1994年,Erwin Unruh采用Metaware 编译器编译出错信息如下(以及其它一些信息,简短起见,它们被删除了): 

23 | Type `enum{}´ can´t be converted to txpe `D<2>´ ("primes.cpp",L2/C25).

24 | Type `enum{}´ can´t be converted to txpe `D<3>´ ("primes.cpp",L2/C25).

25 | Type `enum{}´ can´t be converted to txpe `D<5>´ ("primes.cpp",L2/C25).

26 | Type `enum{}´ can´t be converted to txpe `D<7>´ ("primes.cpp",L2/C25).

复制代码

如今,上面的代码已经不再是合法的C++程序了。以下是Erwin Unruh亲手给出的修订版,可以在今天符合标准的C++编译器上进行编译: 

27 // Prime number computation by Erwin Unruh

28 

29 template <int i> struct D { D(void*); operator int(); };

30 

31 template <int p, int i> struct is_prime {

32     enum { prim = (p==2) || (p%i) && is_prime<(i>2?p:0), i-1> :: prim };

33 };

34 

35 template <int i> struct Prime_print {

36 Prime_print<i-1> a;

37     enum { prim = is_prime<i, i-1>::prim };

38     void f() { D<i> d = prim ? 1 : 0; a.f();}

39 };

40 

41 template<> struct is_prime<0,0> { enum {prim=1}; };

42 template<> struct is_prime<0,1> { enum {prim=1}; };

43 

44 template<> struct Prime_print<1> {

45     enum {prim=0};

46     void f() { D<1> d = prim ? 1 : 0; };

47 };

48 

49 #ifndef LAST

50 #define LAST 18

51 #endif

52 

53 main() {

54     Prime_print<LAST> a;

55     a.f();

56 }

复制代码

GNU C++ (MinGW Special) 3.2中编译这段程序时,编译器将会给出如下出错信息(以及其它一些信息,简短起见,它们被删除了): 

57 Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 17]'

58 Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 13]'

59 Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 11]'

60 Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 7]'

61 Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 5]'

62 Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 3]'

63 Unruh.cpp:12: initializing argument 1 of `D<i>::D(void*) [with int i = 2]'

复制代码

这个例子展示了可以利用模板实例化机制于编译期执行一些计算。这种通过模板实例化而执行的特别的编译期计算技术即被称为模板元编程。

顺便说一句,因为编译器的出错信息并未被标准化,所以,如果你在Visual C++Borland C++等编译器上看不到这么详细的出错信息,请不必讶异。

一个可以运行的模板元编程例子

模板元编程(Template Metaprogramming)更准确的含义应该是可以编程序的程序,而模板元程序(Template Metaprogram)则是“‘可以编程序的程序。也就是说,我们给出代码的产生规则,编译器在编译期解释这些规则并生成新代码来实现我们预期的功能。

Erwin Unruh的那段经典代码并没有执行,它只是以编译出错信息的方式输出中间计算结果。让我们来看一个可以运行的模板元编程例子 — 计算给定整数的指定次方: 

64 // xy.h

65 

66 //原始摸板

67 template<int Base, int Exponent>

68 class XY

69 {

70 public:

71     enum { result_ = Base * XY<Base, Exponent-1>::result_ };

72 };

73 

74 //用于终结递归的局部特化版

75 template<int Base>

76 class XY<Base, 0>

77 {

78 public:

79     enum { result_ = 1 };

80 };

复制代码

模板元编程技术之根本在于递归模板实例化。第一个模板实现了一般情况下的递归规则。当用一对整数<X, Y>来实例化模板时,模板XY<X, Y>需要计算其result_的值,将同一模板中针对<X, Y-1>实例化所得结果乘以X即可。第二个模板是一个局部特化版本,用于终结递归。

让我们看看使用此模板来计算5^4 (通过实例化XY<5, 4>)时发生了什么: 

81 // xytest.cpp

82 

83 #include <iostream>

84 #include "xy.h"

85 

86 int main()

87 {

88     std::cout << "X^Y<5, 4>::result_ = " << XY<5, 4>::result_;

89 }

复制代码

首先,编译器实例化XY<5, 4>,它的result_5 * XY<5, 3>::result_,如此一来,又需要针对<5, 3>实例化同样的模板,后者又实例化XY<5, 2>…… 当实例化到XY<5, 0>的时候,result_的值被计算为1,至此递归结束。

递归模板实例化的深度和终结条件

可以想象,如果我们以非常大的Y值来实例化类模板XY,那肯定会占用大量的编译器资源甚至会迅速耗尽可用资源(在计算结果溢出之前),因此,在实践中我们应该有节制地使用模板元编程技术。

虽然 C++标准建议的最小实例化深度只有17层,然而大多数编译器都能够处理至少几十层,有些编译器允许实例化至数百层,更有一些可达数千层,直至资源耗尽。

假如我们拿掉XY模板局部特化版本,情况会如何? 

90 // xy2.h

91 

92 //原始摸板

93 template<int Base, int Exponent>

94 class XY

95 {

96 public:

97     enum { result_ = Base * XY<Base, Exponent-1>::result_ };

98 };

复制代码

测试程序不变: 

99 // xytest2.cpp

100 

101 #include <iostream>

102 #include "xy2.h"

103 

104 int main()

105 {

106     std::cout << "X^Y<5, 4>::result_ = " << XY<5, 4>::result_;

107 }

复制代码

执行如下编译命令:

C:\>g++ -c xytest2.cpp

你将会看到递归实例化将一直进行下去,直到达到编译器的极限。

GNU C++ (MinGW Special) 3.2的默认实例化极限深度为500层,你也可以手工调整实例化深度:

C:\>g++ -ftemplate-depth-3400 -c xytest2.cpp

事实上,就本例而言,g++ 3.2允许的实例化极限深度还可以再大一些(我的测试结果是不超过3450层)。

因此,在使用模板元编程技术时,我们总是要给出原始模板的特化版(局部特化版或完全特化版或兼而有之),以作为递归模板实例化的终结准则。

利用模板元编程技术解开循环

模板元编程技术最早的实际应用之一是用于数值计算中的解循环。举个例子,对一个数组进行求和的常见方法是: 

108 // sumarray.h

109 

110 template <typename T>

111 inline T sum_array(int Dim, T* a)

112 {

113     T result = T();

114     for (int i = 0; i < Dim; ++i)

115     {

116         result += a[i];

117     }

118     return result;

119 }

复制代码

这当然可行,但我们也可以利用模板元编程技术来解开循环: 

120 // sumarray2.h

121 

122 // 原始模板

123 template <int Dim, typename T>

124 class Sumarray

125 {

126 public:

127     static T result(T* a)

128     {

129         return a[0] + Sumarray<Dim-1, T>::result(a+1);

130     }

131 };

132 

133 // 作为终结准则的局部特化版

134 template <typename T>

135 class Sumarray<1, T>

136 {

137 public:

138     static T result(T* a)

139     {

140         return a[0];

141     }

142 };

复制代码

用法如下: 

143 // sumarraytest2.cpp

144 

145 #include <iostream>

146 #include "sumarray2.h"

147 

148 int main()

149 {

150     int a[6] = {1, 2, 3, 4, 5, 6};

151     std::cout << " Sumarray<6>(a) = " << Sumarray<6, int>::result(a);

152 }

复制代码

当我们计算Sumarray<6, int>::result(a)时,实例化过程如下: 

153 Sumarray<6, int>::result(a)

154 = a[0] + Sumvector<5, int>::result(a+1)

155 = a[0] + a[1] + Sumvector<4, int>::result(a+2)

156 = a[0] + a[1] + a[2] + Sumvector<3, int>::result(a+3)

157 = a[0] + a[1] + a[2] + a[3] + Sumvector<2, int>::result(a+4)

158 = a[0] + a[1] + a[2] + a[3] + a[4] + Sumvector<1, int>::result(a+5)

159 = a[0] + a[1] + a[2] + a[3] + a[4] + a[5]

复制代码

可见,循环被展开为a[0]  + a[1] + a[2] + a[3] + a[4] + a[5]。这种直截了当的展开运算几乎总是比循环来得更有效率。

也许拿一个有着600万个元素的数组来例证循环开解的优势可能更有说服力。生成这样的数组很容易,有兴趣,你不妨测试、对比一下。

(感谢一位朋友的测试。他说 ,据在Visual C++ 2003上实测编译器应当进行了尾递归优化,可以不受上面说的递归层次的限制,然而连加的结果在数组个数达到4796之后就不再正确了,程序输出了空行,已经出错” — 20031230日补充)

模板元编程在数值计算程序库中的应用

Blitz++之所以快如闪电(这正是blitz的字面含义),离不开模板元程序的功劳。Blitz++淋漓尽致地使用了元编程技术,你可以到这些文件源代码中窥探究竟:

· dot.h

· matassign.h

· matmat.h

· matvec.h

· metaprog.h

· product.h

· sum.h

· vecassign.h


让我们看看Blitz++程序库dot.h文件中的模板元程序: 

160 template<int N, int I>

161 class _bz_meta_vectorDot {

162 public:

163     enum { loopFlag = (I < N-1) ? 1 : 0 };

164 

165     template<class T_expr1, class T_expr2>

166     static inline BZ_PROMOTE(_bz_typename T_expr1::T_numtype, _bz_typename T_expr2::T_numtype)

167     f(const T_expr1& a, const T_expr2& b)

168     {

169         return a[I] * b[I] + _bz_meta_vectorDot<loopFlag * N, loopFlag * (I+1)>::f(a,b);

170     }

171 

172     template<class T_expr1, class T_expr2>

173     static inline BZ_PROMOTE(_bz_typename T_expr1::T_numtype, _bz_typename T_expr2::T_numtype)

174     f_value_ref(T_expr1 a, const T_expr2& b)

175     {

176         return a[I] * b[I] + _bz_meta_vectorDot<loopFlag * N, loopFlag * (I+1)>::f(a,b);

177     }

178 

179     template<class T_expr1, class T_expr2>

180     static inline BZ_PROMOTE(_bz_typename T_expr1::T_numtype, _bz_typename T_expr2::T_numtype)

181     f_ref_value(const T_expr1& a, T_expr2 b)

182     {

183         return a[I] * b[I] + _bz_meta_vectorDot<loopFlag * N, loopFlag * (I+1)>::f(a,b);

184     }

185 

186     template<class T_expr1, class P_numtype2>

187     static inline BZ_PROMOTE(_bz_typename T_expr1::T_numtype, P_numtype2)

188     dotWithArgs(const T_expr1& a, P_numtype2 i1, P_numtype2 i2=0,

189                 P_numtype2 i3=0, P_numtype2 i4=0, P_numtype2 i5=0, P_numtype2 i6=0,

190                 P_numtype2 i7=0, P_numtype2 i8=0, P_numtype2 i9=0, P_numtype2 i10=0)

191     {

192         return a[I] * i1 + _bz_meta_vectorDot<loopFlag * N, loopFlag * (I+1)>::dotWithArgs

193                                                                                    (a, i2, i3, i4, i5, i6, i7, i8, i9);

194     }

195 };

196 

197 template<>

198 class _bz_meta_vectorDot<0,0> {

199 public:

200     template<class T_expr1, class T_expr2>

201     static inline _bz_meta_nullOperand f(const T_expr1&, const T_expr2&)

202     { return _bz_meta_nullOperand(); }

203 

204     template<class T_expr1, class P_numtype2>

205     static inline _bz_meta_nullOperand

206     dotWithArgs(const T_expr1& a, P_numtype2 i1, P_numtype2 i2=0,

207                 P_numtype2 i3=0, P_numtype2 i4=0, P_numtype2 i5=0, P_numtype2 i6=0,

208                 P_numtype2 i7=0, P_numtype2 i8=0, P_numtype2 i9=0, P_numtype2 i10=0)

209     {

210         return _bz_meta_nullOperand();

211     }

212 };

复制代码

这段代码远比它乍看上去的简单。_bz_meta_vectorDot类模板使用了一个临时变量loopFlag来存放每一步循环条件的评估结果,并使用了一个完全特化版作为递归终结的条件。需要说明的是,和几乎所有元程序一样,这个临时变量作用发挥于编译期,并将从运行代码中优化掉。

Todd是在Blitz++数值数组库的主要作者。这个程序库(以及MTLPOOMA等程序库)例证了模板元程序可以为我们带来更加高效的数值计算性能。Todd宣称Blitz++的性能可以和对应的Fortran程序库媲美。

Loki程序库:活用模板元编程技术的典范

模板元编程的价值仅仅在于高性能数值计算吗?不仅如此。Loki程序库以对泛型模式的开创性工作闻名于C++社群。它很巧妙地利用了模板元编程技术实现了Typelist组件。Typelist是实现Abstract FactoryVisitor等泛型模式不可或缺的基础设施。

就像C++标准库组件std::list提供对一组数值的操作一样,Typelist可以用来操纵一组类型,其定义非常简单(摘自Loki程序库Typelist.h单元): 

213 template <class T, class U>

214 struct Typelist

215 {

216     typedef T Head;

217     typedef U Tail;

218 };

复制代码

显然,Typelist没有任何状态,也未定义任何操作,其作用只在于携带类型信息,它并未打算被实例化,因此,对于Typelist的任何处理都必然发生于编译期而非运行期。

Typelist可以被无限扩展,因为模板参数可以是任何类型(包括该模板的其他具现体)。例如: 

219 Typelist<char, Typelist<int, Typelist<float, NullType> > >  

复制代码

就是一个包含有charintfloat三种类型的Typelist

按照Loki的约定,每一个Typelist都必须以NullType结尾。NullType的作用类似于传统C字符串的“\0”,它被声明于Loki程序库的NullType.h文件中: 

220 class NullType;

复制代码

NullType只有声明,没有定义,因为Loki程序库永远都不需要创建一个NullType对象。

让我们看看IndexOf模板元程序,它可以在一个Typelist中查找给定类型的位置(摘自Loki程序库的Typelist.h单元): 

221 template <class TList, class T>

222 struct IndexOf;

223 

224 template <class T>

225 struct IndexOf<NullType, T>

226 {

227     enum { value = -1 };

228 };

229 

230 template <class T, class Tail>

231 struct IndexOf<Typelist<T, Tail>, T>

232 {

233     enum { value = 0 };

234 };

235 

236 template <class Head, class Tail, class T>

237 struct IndexOf<Typelist<Head, Tail>, T>

238 {

239 private:

240     enum { temp = IndexOf<Tail, T>::value };

241 public:

242     enum { value = (temp == -1 ? -1 : 1 + temp) };

243 };

复制代码

IndexOf 提供了一个原始模板和三个局部特化版。算法非常简单:如果TList(就是一个Typelist)是一个NullType,则value-1。如果 TList的头部就是T,则value0。否则将IndexOf施行于TList的尾部和T,并将评估结果置于一个临时变量temp中。如果temp为 -1,则value-1,否则value1 + temp

为了加深你对Typelist采用的模板元编程技术的认识,我从Loki程序库剥离出如下代码,放入一个typelistlite.h文件中: 

244 // typelistlite.h

245 

246 // 声明Nulltype

247 class NullType;

248 

249 // Typelist的定义

250 template <class T, class U>

251 struct Typelist

252 {

253     typedef T Head;

254     typedef U Tail;

255 };

256 

257 // IndexOf的定义

258 

259 // IndexOf原始模板

260 template <class TList, class T> struct IndexOf;

261 

262 // 针对NullType的局部特化版

263 template <class T>

264 struct IndexOf<NullType, T>

265 {

266     enum { value = -1 };

267 };

268 

269 // 针对TList头部就是我们要查找的T的局部特化版

270 template <class T, class Tail>

271 struct IndexOf<Typelist<T, Tail>, T>

272 {

273     enum { value = 0 };

274 };

275 

276 // 处理TList尾部的局部特化版

277 template <class Head, class Tail, class T>

278 struct IndexOf<Typelist<Head, Tail>, T>

279 {

280 private:

281     enum { temp = IndexOf<Tail, T>::value };

282 public:

283     enum { value = (temp == -1 ? -1 : 1 + temp) };

284 };

复制代码

测试程序如下: 

285 // typelistlite_test.cpp

286 

287 #include <iostream>

288 #include "typelistlite.h"

289 

290 // 自定义类型Royal

291 class Royal {};

292 

293 // 定义一个包含有charintRoyalfloatTypelist

294 typedef Typelist<char, Typelist<int, Typelist<Royal, Typelist<float, NullType> > > > CIRF;

295 

296 int main()

297 {

298     std::cout << "IndexOf<CIRF, int>::value = " << IndexOf<CIRF, int>::value << "\n";

299     std::cout << "IndexOf<CIRF, Royal>::value = " << IndexOf<CIRF, Royal>::value << "\n";

300     std::cout << "IndexOf<CIRF, double>::value = " << IndexOf<CIRF, double>::value << "\n";

301 }

复制代码

程序输出如下: 

302 IndexOf<CIRF, int>::value = 1

303 IndexOf<CIRF, Royal>::value = 2

304 IndexOf<CIRF, double>::value = -1

复制代码

结语

模板元编程技术并非都是优点,比方说,模板元程序编译耗时,带有模板元程序的程序生成的代码尺寸要比普通程序的大,而且通常这种程序调试起来也比常规程序困难得多。另外,对于一些程序员来说,以类模板的方式描述算法也许有点抽象。

编译耗时的代价换来的是卓越的运行期性能。通常来说,一个有意义的程序的运行次数(或服役时间)总是远远超过编译次数(或编译时间)。为程序的用户带来更好的体验,或者为性能要求严格的数值计算换取更高的性能,值得程序员付出这样的代价。

很难想象模板元编程技术会成为每一个普通程序员的日常工具,相反,就像Blitz++Loki那样,模板元程序几乎总是应该被封装在一个程序库的内部。对于库的用户来说,它应该是透明的。模板元程序可以(也应该)用作常规模板代码的内核,为关键的算法实现更好的性能,或者为特别的目的实现特别的效果。

模板元编程技术首次正式亮相于Todd Veldhuizen的《Using C++ Template Metaprograms》论文之中。这篇文章首先发表于19955月的C++ Report期刊上,后来Stanley Lippman编辑《C++ Gems》一书时又收录了它。参考文献中给出了这篇文章的链接,它还描述了许多本文没有描述到的内容。

David VandevoordeNicolai M. Josuttis合著的《C++ Templates: The Complete Guide》一书花了一整章的篇幅介绍模板元编程技术,它同样是本文的参考资料并且也应该作为你的补充阅读材料。

Andrei Alexandrescu的天才著作《Modern C++ Design: Generic Programming and Design Patterns Applied》的第3TypelistsTypelist有着更为详尽的描述。

参考文献和资源

1. David Vandevoorde, Nicolai M. Josuttis, C++ Templates: The Complete Guide, Addison Wesley, 2002.
2.  Andrei Alexandrescu, Modern C++ Design: Generic Programming and Design Patterns Applied, Addison Wesley, 2001.
3. 侯捷 於春景 译,《C++设计新思维》,华中科技大学出版社,2003
4. Todd Veldhuizen, Template Metaprograms, http://osl.iu.edu/~tveldhui/pape ... grams/meta-art.html .
5. Todd Veldhuizen, C++ templates as partial evaluation (PEPM99), http://osl.iu.edu/~tveldhui/papers/pepm99/.
6. Erwin Unruh, Prime numbers(Primzahlen - Original), http://www.erwin-unruh.de/primorig.html .
7. Erwin Unruh, Prime numbers(Primzahlen), http://www.erwin-unruh.de/Prim.html .
8. Blitz++, http://www.oonumerics.org/blitz .
9. Loki, http://sourceforge.net/projects/loki-lib .
10. POOMA, http://www.pooma.com.
11. MinGW - Minimalist GNU for Windows, http://sourceforge.net/projects/mingw.

 posted on 2012-05-23 10:01  zssure  阅读(544)  评论(0编辑  收藏  举报