One of the more prominent extension libraries to C++ is the Boost library (or I should say libraries, as it is more of a collection libraries). If you're not familiar with this and you work with C++ at all, you should definitely take a look at this guy. Or if you're someone who tends to bash static languages, you should educate yourself a little on what they are capable of.
The boost::any class is a class that can hold a value of any type. For example:
any x = 5;Of course, it is not always so easy. There are a few problems. One, if you want to use the value anywhere, you need to cast to the needed type:
// .. do some stuff with x
x = string("awesome");
any x = 5;You can't put arrays in. Doesn't stop you from putting a pointer to the first element, but it is a little annoying:
cout << any_cast<int>(x) << endl;
int y[] = {1, 2, 3, 4};Despite it being annoying, it gives you a whole heck of a lot of flexibility compared to pure static types, and more security over void pointers. The any_cast function throws an exception if you try to cast to something that isn't compatible.
any x = &y[0];
cout << any_cast<int *>(x)[0] << endl;
This isn't the same as an actual dynamic language, but it is a nice little trick to have in your toolbox when programming in C++.
1 comment:
You can also have the best of both worlds with boost. If you need dynamically typed variables but need to be restricted to a few specific types, you can use the boost variant class. e.g.
variant<int,float,string> x;
x = 1;
x = 2.3;
x = "hello";
Post a Comment