Aug 13, 2008

Dynamic Typing in...C++?

This may be old news to the C++ folks, but to users of dynamic languages like Ruby or PHP who tend to look down on C++/Java for their static nature, this is definitely a welcome aspect.

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;
// .. do some stuff with x
x = string("awesome");
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:
any x = 5;

cout << any_cast<int>(x) << endl;
You can't put arrays in. Doesn't stop you from putting a pointer to the first element, but it is a little annoying:
int y[] = {1, 2, 3, 4};
any x = &y[0];

cout << any_cast<int *>(x)[0] << endl;
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.

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:

fgb said...

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";