c++boostboost-any

Different key type in a map


for a particular requirement I want to have a map with keys in different type. Similar to boost:any. (I have an old gcc version)

map<any_type,string> aMap;

//in runtime :
aMap[1] = "aaa";
aMap["myKey"] = "bbb";

is this something possible with the use boost ?

thank in advance


Solution

  • If you're not willing to use boost variant, you can hack your own key type.

    You could use a discriminated union, or go low-tech en simply use a pair of std::string and int:

    Live On Coliru

    #include <map>
    #include <tuple>
    #include <iostream>
    
    struct Key : std::pair<int, std::string> {
        using base = std::pair<int, std::string>;
        Key(int i) : base(i, "") {}
        Key(char const* s) : base(0, s) {}
        Key(std::string const& s) : base(0, s) {}
    
        operator int() const         { return base::first; }
        operator std::string() const { return base::second; }
        friend bool operator< (Key const& a, Key const& b) { return std::tie(a.first, a.second) <  std::tie(b.first, b.second); }
        friend bool operator==(Key const& a, Key const& b) { return std::tie(a.first, a.second) == std::tie(b.first, b.second); }
        friend std::ostream& operator<<(std::ostream& os, Key const& k) {
            return os << "(" << k.first << ",'" << k.second << "')";
        }
    };
    
    using Map = std::map<Key, std::string>;
    
    int main()
    {
        Map m;
    
        m[1] = "aaa";
        m["myKey"] = "bbb";
    
        for (auto& pair : m)
            std::cout << pair.first << " -> " << pair.second << "\n";
    }
    

    Prints:

    (0,'myKey') -> bbb
    (1,'') -> aaa