这个模板创建的实际源代码是什么样子的?

What will the actual source code this template creates look like?

本文关键字:源代码 什么样 创建      更新时间:2023-10-16
template <int N>
struct Factorial {
    enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0> {
    enum { value = 1 };
};

const int x = Factorial<4>::value; // == 24
const int y = Factorial<0>::value; // == 1

预编译后,如果我们能神奇地看到编译器生成的结果,我们真的会看到:

const int x = 24;
const int y = 1;

我们会看到struct Factorial的实际定义,这些的倍数吗?如果是这样,它们看起来会是什么样子?

在此代码上使用g++ -fdump-tree-original,我看到以下结果,对于这种情况似乎证实了您的怀疑:

;; Function int main() (null)
;; enabled by -tree-original

{
  const int x = 24;
  const int y = 1;
  <<cleanup_point   const int x = 24;>>;
  <<cleanup_point   const int y = 1;>>;
}
return <retval> = 0;