gpt4 book ai didi

c++ - 初始化 C++ 后更改变量类型

转载 作者:搜寻专家 更新时间:2023-10-30 23:53:45 25 4
gpt4 key购买 nike

我来自 node.js,我想知道是否有一种方法可以在 C++ 中执行此操作。什么是 C++ 等效于:

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

所以在 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?
}

我正在使用 JSON,我需要枚举一些字符串。我确实意识到我可以将 return_int() 的返回值分配给另一个变量,但我想知道是否可以为了学习而将变量类型从字符串重新分配给 int和可读性。

最佳答案

C++ 语言本身不允许这样做。变量不能改变它们的类型。但是,您可以使用允许其数据动态更改类型的包装类,例如 boost::anyboost::variant (C++17 添加了 std::anystd::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
}

关于c++ - 初始化 C++ 后更改变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38537156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com