Hi,
I am wondering if type can be determined as runtime information in C++.
(1) Although my question is quite general, for simplicity, I will start from a simple example:
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char * argv[])
{
if (strcmp(argv[1], "int")==0)
{
int t = 2;
}else if (strcmp(argv[1], "float")==0)
{
float t = 2.2;
}
cout << t << endl; // error: ‘t’ was not declared in this scope
return 0;
}
For this example, there are two questions:
(a) "argv[1] to t" is wrong, but can the type info in the C string argv[1] be converted to the actual type keyword? So we don't need to check for every type by if-else clause and strcmp.
(b) how to make variable t defined inside the local scope of the if clause still valid outside. i.e how to "export" a local variable to the outside of its scope?
(2) Generally speaking, not specific to the simple example above, what are the usual ways to runtime determine types? It seems to me that there might be some ways:
(a) one can put the processing of the variable defined from the type inside the same scope its definition. e.g.
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char * argv[])
{
if (strcmp(argv[1], "int")==0)
{
int t = 2;
cout << t << endl;
}else if (strcmp(argv[1], "float")==0)
{
float t = 2.2;
cout << t << endl;
}
return 0;
}
And possibly use template function to make the common code for various types reusable.
(b) or one may use abstract class type and polymorphism to indirectly export the definition out, but I am not sure how exactly.
Thanks for your advice!