Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

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

After pre-compilation, if we could magically see what the compiler produced, would we actually see:

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

And would we see actual definitions for the struct Factorial, multiple of these? If so how would they look? I'm trying wrap my head around this part of the metaprogramming process.

like image 498
johnbakers Avatar asked May 26 '13 02:05

johnbakers


People also ask

What is source code template?

A source template is a reusable source code configuration that defines a source-code build type. Source templates can be used by any project that requires the same source type.


1 Answers

Using g++ -fdump-tree-original on this code, I see the following result, which for this case seems to confirm your suspicion:

;; 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;
like image 95
Shafik Yaghmour Avatar answered Oct 05 '22 23:10

Shafik Yaghmour