Changing variable types after initialization C++

14,583

Solution 1

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
}

Solution 2

That is not possible. C++ is a statically typed language, i.e. types can not change. This will not work with auto or any other way. You will have to use a different variable for the int. In C++11 and newer, you can do:

std::string str = "hello";
auto i = return_int(str);

Or:

int i = return_int(str);

Anyway, calling an integer "string" is a little weird, if you ask me.

Share:
14,583
TeeraMusic
Author by

TeeraMusic

Updated on June 26, 2022

Comments

  • TeeraMusic
    TeeraMusic almost 2 years

    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.