Tee*_*sic 2 c++ variables variable-types
我来自node.js,我想知道是否可以用C ++做到这一点。C ++等效于什么:
var string = "hello";
string = return_int(string); //function returns an integer
// at this point the variable string is an integer
Run Code Online (Sandbox Code Playgroud)
所以在C ++中我想做这样的事情...
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?
}
Run Code Online (Sandbox Code Playgroud)
我正在使用JSON,我需要枚举一些字符串。我确实意识到我可以只将返回值分配return_int()给另一个变量,但是我想知道是否有可能为了学习和可读性而将变量的类型从字符串重新分配给int。
C ++语言本身没有任何东西允许这样做。变量不能更改其类型。但是,您可以使用包装器类,该包装器类允许其数据动态更改类型,例如boost::any或boost::variant(C ++ 17的add std::any和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
}
Run Code Online (Sandbox Code Playgroud)
#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
}
Run Code Online (Sandbox Code Playgroud)