The below program calculates 2 raised to the power n without using any loop,runtime recursion or library function[pow].
It uses TEMPLATE METAPROGRAMMING technique.
#include <iostream>
using namespace std;
template<int n> struct funStruct
{
enum { val = 2*funStruct<n-1>::val };
};
template<> struct funStruct<0>
{
enum { val = 1 };
};
int main()
{
cout << funStruct<8>::val << endl;
return 0;
}
I was wandering that can i use function in place of structure?
The obvious solution, as @tdammes points out is just a non-iterative non-recursive approach:
By using
constexprthe compiler will compute the result at compile time and yield a compile time constant. If you still want to use recursion, you can:Which is basically the same compile time recursion than your metaprogramming trick in a slightly more concise and easy to read manner. The use of
constexpr, of course, requires C++11, so if you don’t have it, you can always use either the original metaprogramming trick, or @tdammers approach adapted: