Access variable value using string representing variable's name in C++ [duplicate]

As has been mentioned, you are looking for reflection in C++. It doesn't have that, and this answer explains why.


You can use an associative container as a std::map< std::string, your_variable_type > to link a string to a variable, assuming they are all of the same type.

If you have variable of different types, solution exists, as in boost::variant


No, not with C++ or its standard library. Of course, you can hack something up to emulate this behaviour. C++ allows you to choose methods at runtime, using polymorphism, so you can take advantage of that. In essence, you'll get the method to invoke at runtime, rather than the variable, and the method will return the vlaue:

struct Value {
    virtual ~Value();
    virtual std::string value() const = 0;
};

struct Counter : public Value {
    int v;
    std::string value() const {
        istringstream ss(v);
        return ss.str();
    }
};

struct Mounter : public Value {
    double v;
    std::string value() const {
        istringstream ss(v);
        return ss.str();
    }
};

Value* get_value();

// ...
cout << get_value()->value() << endl;

Alternatively, you can maintain a map keyed on strings, the names of the values, and then look up the values with their names.