How to understand output result using C ++ templates

I have written even / odd number judgment code with C ++ patterns.

#include <iostream>

template <int N, int Mod2=N%2>
struct Print {
  Print() {
    std::cout << N << std::endl;
  }
};

template <int N>
struct Print<N, 0> {
  Print() {
    std::cout << "Even!" << std::endl;
  }
};

template <int N>
struct Print<N, 1> {
  Print() {
    std::cout << "Odd!" << std::endl;
  }
};

template <int N>
struct EvenOdd {
  EvenOdd() {
    EvenOdd<N+1>();
    Print<N>();
  }
};

template <>
struct EvenOdd<10> {
  EvenOdd() {
    std::cout << "Hey!" << std::endl;
  }
};

int main()
{
  EvenOdd<0>();
  return 0;
}

This code outputs:

$ ./a.out
Hey!
Odd!
Even!
Odd!
Even!
Odd!
Even!
Odd!
Even!
Odd!
Even!

I predicted that

EvenOdd <10> :: EvenOdd () // => "Hey!"
called the last. But, this is a mistake.

Why "hey!" conclusion first?

+3
source share
2 answers

This behavior has nothing to do with patterns. This is the main recursion. You recursively create an instance EvenOddbefore printing. So, the first copy to print is the innermost one EvenOdd<10>.

: EvenOdd<0> EvenOdd<1>. , Print<0>. , EvenOdd<1> EvenOdd<2> , :

EvenOdd<0>
 EvenOdd<1>
  EvenOdd<2>
   EvenOdd<3>
    EvenOdd<4>
     EvenOdd<5>
      EvenOdd<6>
       EvenOdd<7>
        EvenOdd<8>
         EvenOdd<9>
          EvenOdd<10>
          std::cout << "Hey!" << std::endl;
         Print<9>
        Print<8>
       Print<7>
      Print<6>
     Print<5>
    Print<4>
   Print<3>
  Print<2>
 Print<1>
Print<0>
+8

EvenOdd 10, EvenOdd N+1 .

, EvenOdd EvenOdd 10 , - EvenOdd Print.

11- EvenOdd "Hey!", Print.

+6

Source: https://habr.com/ru/post/1725123/


All Articles