Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-style variables in C++

I'm working on a C++ project and am trying to figure out how to make a "dynamic" variable.

In Python, variables can have multiple types:

variable = 0
variable = "Hello"

In Java, this is also (somewhat) achievable:

Object o = 0;
o = "Hello";

From what I can find related to C++, there is no object type or "dynamic" object at that.

The reason I need this, is I'm trying to create an object which takes in any of the following types: int, float, char, string, bool, and allow me to do operations such as:

object o = 0; // currently an int
o -= 2.5; // now a float
o += "Test"; // now a string

Is there any default functionality for this kind of variable? If not, can it be done with macros, struct's, etc.?

I've found things like this:

template <typename name>

But have no idea how to use it.


1 Answers

You can use boost.variant library. Basic usage instructions here. In short, it would be something like

using var_t = boost::variant<bool,int,double,string, boost::blank_t>;
var_t var = "hello";
std::cout << boost::get<std::string>(var) << '\n';
std::cout << var << '\n'; // if all possible stored types are streamable

Somewhat non-straightforward part is accessing value without knowing the exact type. This requires static visitor.

In case you wonder what the difference is between any and variant - you are not alone, and here is the comparison chart.

like image 190
bobah Avatar answered Apr 23 '26 22:04

bobah



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!