Archive

Posts Tagged ‘boost’

Anything, anything!

March 16th, 2008

A very usefull ‘feature’ of some languages is the ability to store values of different types in the same variable. Although this is generally a ‘bad idea’, since it makes it impossible to check for assignment errors during compile-time.

However, there are cases where it is very usefull; for instance, lets say that you are writing something that stores a key/value pair of data of which value can be any given type, perhaps you are writing a HTTP server where you want to store some objects between requests.

In the Java world everything inherits from Object, making the HttpSession nothing more then a Map of String keys and Object values. In C++ we do not have such a common parent, so we cannot store multiple types into the same map.

In the Boost libraries there is something called boost::any. The easiest way to illustrate this is by showing an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <boost>
#include <iostream>
#include <string>
 
int main(int argc, char *argv[]) {
    std::string string = "this is a string";
    int integer = 42;
 
    boost::any test = integer;
    std::cout << "An int: " << boost::any_cast<int>(test) << std::endl;
 
    test = string;
    std::cout << "A string: " << boost::any_cast<std::string>(test)
              << std::endl;
 
    try {
      int no = boost::any_cast<int>(test);
    } catch (boost::bad_any_cast &amp;ex) {
      std::cout << "Cannot cast a string to an int: "
                << ex.what() << std::endl;
    }
}

As you can see, the variable test, which is of type boost::any, can contain any other type and can easily be cast back to the original type (lines 9 and 12). Casting a boost::any to an inconvertible type will cause a boost::bad_any_cast.

Code , ,