tags:

views:

290

answers:

3

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!

+4  A: 

You need a class that's capable of storing a value of different types. Short from a union, Boost's variant class would be the proper choice.

Hans Passant
if not using boost?
Tim
As I mentioned, a union.
Hans Passant
+2  A: 

Check out Boost.Variant.

R Samuel Klatchko
+5  A: 
Roger Pate
+1 I was going to post the polymorphic solution. Makes much more sense than boost.variant because with boost.variant you'd need to check the type for every operation.
Stefan Monov