Search code examples
c++variablesvariable-types

Changing variable types after initialization C++


I'm coming from node.js and I was wondering if there is a way to do this in C++. What would be the C++ equivalent of:

var string = "hello";
string = return_int(string); //function returns an integer
// at this point the variable string is an integer

So in C++ I want to do something kind of like this...

int return_int(std::string string){
     //do stuff here
     return 7; //return some int
}
int main(){
    std::string string{"hello"};
    string = return_int(string); //an easy and performant way to make this happen?
}

I'm working with JSON and I need to enumerate some strings. I do realize that I could just assign the return value of return_int() to another variable, but I want to know if it's possible to reassign the type of variable from a string to an int for sake of learning and readability.


Solution

  • There is nothing in the C++ language itself that allows this. Variables can't change their type. However, you can use a wrapper class that allows its data to change type dynamically, such as boost::any or boost::variant (C++17 adds std::any and std::variant):

    #include <boost/any.hpp>
    
    int main(){
        boost::any s = std::string("hello");
        // s now holds a string
        s = return_int(boost::any_cast<std::string>(s));
        // s now holds an int
    }
    

    #include <boost/variant.hpp>
    #include <boost/variant/get.hpp>
    
    int main(){
        boost::variant<int, std::string> s("hello");
        // s now holds a string
        s = return_int(boost::get<std::string>(s));
        // s now holds an int
    }