I wrote a judgment code of even/odd numbers with C++ templates.
#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!"is called lastly. But, it's mistake.
Why does "Hey!" output firstly?