Here is the code for templates specilization:
template <int i>
struct userInput{};
template <>
struct userInput<1>
{
typedef int typeName;
};
template <>
struct userInput<2>
{
typedef double typeName;
};
And I want to choose the appropriate template according to the user input:
int i;
std::cin>>i;
userInput<i>::typeName ty;
But the compiler is not happy with me, it requires a contant value to be passed in to the template parameter.
So I did this:
int i;
std::cin>>i;
const int p = i;
userInput<p>::typeName ty;
However, there is error :template parameter ‘i’ : ‘num’ : a local variable cannot be used as a non-type argument. Anyone can help me out? I’d appreciate it!
You will have to
switchon the input to find the constant value to feed to your template.So, if the input is
1, the output is0. If the input is2, the output is0.5. For others, the error message appears.The difference between the code in
foo, and the code you tried to write is thatfoo<1>andfoo<2>are two different functions, each with a differenttyvariable, and eachtyvariable has a different type. In contrast, your code has a singletyvariable that tries to be both kinds oftypeNames at the same time, sort of like Schroedinger’s Cat. The compiler failed to collapse the waveform, so it complained.