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.
Using
boost::anyas an associative container key is rather inconvenient. For ordered containers it must supportoperator<, for unordered -operator==andstd::hash(or a hash of your choice). You would need to implement this functionality yourself butboost::anydoes not provide a convenient way to query the type of the stored value.An ideal choice is probably
boost::variantfor both key and values, since DBUS has a limited number of types: integers, double, string; dictionaries and variants can be modelled with recursiveboost::variant.Implementing the required operators for
boost::variantis straightforward: compare the value type first and, if they match, the value itself.