template <class option>
option opt (int number, char *variable) {
char *name;
char *type;
switch (number) {
case 2: {
bool *value;
name = "Option 3";
value = false;
type = "bool";
}
break;
case 1: {
char *value;
name = "Option 2";
value = "Hello";
type = "string";
}
break;
default: {
int value;
name = "Option 1";
value = 0;
type = "number";
}
break;
}
if (variable == "name") return type;
elseif (variable == "type") return type;
elsereturn value;
}
Compiler gives this (I omitted the problems from the main function):
Compiling: main.cpp
C:\Users\awsdert\Desktop\SOS\main.cpp: In function `option opt(int, char*)':
C:\Users\awsdert\Desktop\SOS\main.cpp:39: error: `value' was not declared in this scope
Process terminated with status 1 (0 minutes, 0 seconds)
12 errors, 0 warnings
Astonishing timing - as for what it supposed to do, it's to parse cmdline options into, I just needed to read the data first before implimenting writing to the data.
You can't return different types in the same function even using a template.
C++ is not like weakly typed languages such as Javascript.
Each function can only return one type. In a template function, that one type can vary. But within any particular invocation of the template function, only one type can be returned.
You have to remember that when you call your function you need to know the return tybe before you call it:
1 2 3 4 5 6 7
int var = opt (2, "-size");
// need to declare the type of the variable
// that will accept the return value from the function
// BEFORE calling the function.