c++boostboost-any

Type checking of std::map of keys and/or values of type boost::any?


I am writing helper functions which converts DBus properties values to std types. For that, to convert few type, i need to create a std::map. The map will represent DICT type in DBus. The DICT type in DBUS can have any type as a key and any type as it's value. Now, I need to convert it to std::map. I am thinking of using std::map<boost::any, boost::any> for DICT type of DBUS. However, I have to check the type after converting all the types of DBUS to std types. But it looks like i can't do it as the program below fails (obviously):

#include <iostream>
#include <typeinfo>
#include <boost/any.hpp>

#include <map>
#include <string>

int main()
{
    std::map<std::string, boost::any> m;
    boost::any key = 2;
    boost::any value = std::string("Hello");

    m.insert(std::make_pair(std::string("Key"), value));

    if (typeid(m) == typeid(std::map<std::string, std::string>))
        std::cout << "Yes" << std::endl;
    return 0;
}

I am looking for better way to do it.


Solution

  • Using boost::any as an associative container key is rather inconvenient. For ordered containers it must support operator<, for unordered - operator== and std::hash (or a hash of your choice). You would need to implement this functionality yourself but boost::any does not provide a convenient way to query the type of the stored value.

    An ideal choice is probably boost::variant for both key and values, since DBUS has a limited number of types: integers, double, string; dictionaries and variants can be modelled with recursive boost::variant.

    Implementing the required operators for boost::variant is straightforward: compare the value type first and, if they match, the value itself.