Skip to content

Instantly share code, notes, and snippets.

@jeandudey
Created July 14, 2015 14:11
Show Gist options
  • Save jeandudey/89e7f60ad0b709be5e81 to your computer and use it in GitHub Desktop.
Save jeandudey/89e7f60ad0b709be5e81 to your computer and use it in GitHub Desktop.
Is even or odd in C++ template metaprogramming.

Is even or odd?

This is a common exercise implemented in C++11 using template metaprogramming techniques.

Compiling

Just run make in your shell :p

#include <iostream>
template <int a>
struct isodd {
static constexpr bool value = a % 2;
};
template <int a>
struct iseven {
static constexpr bool value = !(a % 2);
};
template <int a>
struct square {
static constexpr int value = a * a;
};
int main() {
auto r1 = iseven< square< 4 >::value >::value;
auto r2 = isodd< square< 3 >::value >::value;
std::cout << r1 << std::endl;
std::cout << r1 << std::endl;
return 0;
}
all:
g++ Main.cc -o isodd -std=c++11
@midjji
Copy link

midjji commented Jan 24, 2017

Why not just
template constexpr int square(){return a *a };
template constexpr bool isodd(){return a % 2 ==1;};
static_assert(isodd<square<4>>,"16 isnt squre?")
Seems much more natural...

well atleast after the markdown is removed...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment