初始化C ++后更改变量类型 [英] Changing variable types after initialization C++

查看:49
本文介绍了初始化C ++后更改变量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自node.js,我想知道在C ++中是否有办法做到这一点.与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

所以在C ++中,我想做这样的事情...

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?
}

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

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.

推荐答案

C ++语言本身没有任何允许这样做的东西.变量不能更改其类型.但是,您可以使用允许其数据动态更改类型的包装器类,例如 boost :: any boost :: variant (C ++ 17添加了 std :: any

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
}

这篇关于初始化C ++后更改变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆