Home c++ -> template meta programming vs template functions
Reply: 0

c++ -> template meta programming vs template functions

user1443 Published in April 24, 2018, 8:35 am

I am learning C++ template meta-programming. I want to know the difference between the following constructs. Suppose the classic example of the factorial.

Example 1

template <int n>
struct factorial
  enum { fac = n*factorial<n-1>::fac };
factorial<4> ex;

(where we omit the termination conditions for brevity.)

Example 2

template<int n> factorial<n> foo1(){return factorial<n>();}

Example 3

template<int n> int foo2(){return n*foo2<n-1>();}
template<> int foo2<0>(){return 1;}
int ex2=foo2<4>()

Example 4

template<int n>
  int foo3(){
    int k=1;
    for(int i=2;i<=n;i++) k*=i;
    return k;
int ex3=foo3<4>();

What are the differences between the 4 examples? In particular, what is done at compile time for each variant?

My Thoughts

It's clear that example 1 is completely compile-time. The second, I think, is also compile-time, but I'm not sure what the compiler does. The third is also at compile time? I'm not certain.

The fourth isn't compile-time. What is done at compile time? Does the compiler create a code-generator for the function, where n is "replaced" by the constant value?

Please correct me, or add to my thoughts.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.375576 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO