Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 784
TeeraMusic Avatar asked May 25 '26 09:05

TeeraMusic


2 Answers

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
}
like image 71
Remy Lebeau Avatar answered May 27 '26 23:05

Remy Lebeau


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.

like image 37
Rudy Velthuis Avatar answered May 27 '26 22:05

Rudy Velthuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!