This is a common exercise implemented in C++11 using template metaprogramming techniques.
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 |
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...