Ray's playground

 

Item 48: Be aware of template metaprogramming(Effective C++)

Template metaprogramming can shift work from runtime to compile-time, thus enabling earlier error detection and higher runtime performance.
TMP can be used to generate custom code based on combinations of policy choices, and it can also be used to avoid generating code inappropriate for particular types.

 1 #include <iostream>
 2 using namespace std;
 3 
 4 template<unsigned n>
 5 struct Factorial
 6 {
 7     enum { value = n * Factorial<n-1>::value };
 8 };
 9 
10 template<>
11 struct Factorial<0>
12 {
13     enum { value = 1 };
14 };
15 
16 int main()
17 {
18     cout << Factorial<10>::value << endl;
19     cout << Factorial<5>::value << endl;
20     cin.get();
21     return 0;
22 }

posted on 2011-04-09 10:39  Ray Z  阅读(158)  评论(0编辑  收藏  举报

导航