Determining runtime for C ++

I am wondering if a type can be defined as C ++ runtime information.

(1) Although my question is quite general, for simplicity I will start with 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;  
 }

There are two questions in this example:

(a) "argv [1] to t" is incorrect, but can the type information in the string C argv [1] be converted to a keyword of the actual type? Therefore, we do not need to check each type with the if-else and strcmp clauses.

(b) how to make the variable t defined inside the local scope of the if still valid outside. For example, how to "export" a local variable outside its scope?

(2) , , ? , :

(a) , . .

 #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;  
 }

, , , .

(b), , , , .

!

+5
3

1a: , ++ ( , , Python). , argv [1].

1b: , .

2: dynamic_cast typeid ( ) , ( , , , ) ( ).

2a: , , , - , , , , . , , , 2a, .

2b: , , :

struct Base {
  virtual ~Base() {}
  friend std::ostream& operator<<(std::ostream& s, Base const& v) {
    v._print(s);
    return s;
  }
private:
  virtual void _print(std::ostream&) const = 0;
};

template<class T>
struct Value : Base {
  T data;
  explicit
  Value(T const& data) : data(data) {}
private:
  virtual void _print(std::ostream& s) const {
    s << data;
  }
};

:

int main(int argc, char** argv) {
  using namespace std;
  auto_ptr<Base> p;
  string const type = argc > 1 ? argv[1] : "int";
  if (type == "int") {
    p.reset(new Value<int>(2));
  }
  else if (type == "float") {
    p.reset(new Value<double>(2.2));
  }
  cout << *p << '\n';
  return 0;
}

, , Base, . , , boost.variant, , .

+7
+5
+2
source

All Articles