条款48:认识 template 元编程

Be aware of template meta-programming.

Template meta-programming(TMP,模板元编程)是编写 template-based C++ 程序并执行于编译期的过程。

TMP 已被证实是个“图灵完全(Turing-complete)机器,意思是它的威力大到足以计算任何事物。例如计算阶乘:

template<unsigned n>
struct Factorial {
    enum { value = n * Factorial<n-1>::value };
};

template<>
struct Factorial<0>
    enum { value = 1 };
};

TMP 之所以值得学习:

  • 确保量度单位正确;

  • 优化矩阵运算;

  • 可以生成客户定制之设计模式;

Last updated

Was this helpful?