You won't be able to use template metaprogramming to evaluate the result of the switch if the value you're switching on (in this case, x) is not known at compile time. This is because templates are blown-out at compile-time, not at run time.
However, if you know the value at compile-time, you can achieve a similar effect:
#include <cstdlib>
#include <iostream>
using namespace std;
template<int V> struct intswitch
{
operator int() const
{
return V * V;
}
};
int main() {
cout << "1 = " << intswitch<1>() << endl
<< "2 = " << intswitch<2>() << endl
<< "3 = " << intswitch<3>() << endl
<< "4 = " << intswitch<4>() << endl
<< "5 = " << intswitch<5>() << endl
<< "6 = " << intswitch<6>() << endl
<< "7 = " << intswitch<7>() << endl
<< "8 = " << intswitch<8>() << endl
<< "9 = " << intswitch<9>() << endl
<< "10 = " << intswitch<10>() << endl
;
}
Program output:
1 = 1
2 = 4
3 = 9
4 = 16
5 = 25
6 = 36
7 = 49
8 = 64
9 = 81
10 = 100