c++模板元编程2:用enum做数值计算

c++模板元编程二:用enum做数值计算

2.1 用enum做数值计算

下面两篇文章都介绍了模板元编程,enum是其最重要的基本工具 http://www.codeproject.com/Articles/3743/A-gentle-introduction-to-Template-Metaprogramming https://www10.informatik.uni-erlangen.de/~pflaum/pflaum/ProSeminar/meta-art.html

因此可以得道以下结论:

  1. enum的值由编译器在编译期计算
  2. 利用模板特化和递归算法,可以让编译器在计算enum值的时候递归产生一系列class

下面是简单的例子, 一个求N的阶乘的代码:

#include <iostream>

template<int N>
class Factorial {
public:
  enum { RESULT = N * Factorial<N - 1>::RESULT };
};

template<>
class Factorial<1> {
public:
  enum { RESULT = 1 };
};

int main(int argc, char ** argv) {
  try {
    std::cout << Factorial<4>::RESULT << std::endl;
  } catch(std::exception const& e) {
    std::cerr << e.what() << std::endl;
  }
}

递归算法让编译器产生Factorial的一系列特化类:Factorial<1>, Factorial<2>, Factorial<3> 和 Factorial<4>。这些产生的类会导致编译出来的程序体积变大,编译期变长,但是运行时却变得非常快。因为运行时已经没有递归,直接获得常量并输出。