#include <iostream> template <int N> struct fact { enum { value = N * fact<N - 1>::value }; }; template <> struct fact<1> { enum { value = 1 }; }; int main() { std::cout << "5! = " << fact<5>::value << std::endl; }jserv@venux:/tmp$ g++ -o factorial factorial.cc
這算是 C++ template 的進階技巧,以下的書籍也有介紹:
* C++ Template: The Complete Guide, Chapter 17, Metaprograms
不過個人認為,除非是為了達到像 Boost 或 Loki 這種程度的 library,否則,這種技巧還是玩玩就好。
由 william 發表於 February 6, 2006 09:38 PM