6
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, 多个这些的实际定义吗?如果是这样,他们会是什么样子?我正在尝试围绕元编程过程的这一部分。

4

1 回答 1

1

使用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;
于 2013-05-26T03:04:03.507 回答