1

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

2 Answers2

2

If you're willing to use boost::variant:

Live On Coliru

#include <boost/variant.hpp>
#include <iostream>
#include <map>

using Key = boost::variant<int, std::string>;
using Map = std::map<Key, std::string>;

int main()
{
    Map m;

    m[1] = "aaa";
    m["myKey"] = "bbb";
}

Key ordering/equation is automatically there. Note though that "1" and 1 are different keys in this approach.

sehe
  • 374,641
  • 47
  • 450
  • 633
  • 1
    Hi, thanks for your answer. as stated in my question, I'm using an old compiler adn requirement is not to use boost. – user3291059 Apr 03 '17 at 02:52
  • 1
    The question was tagged [tag:boost]. The questing text says "is this something possible with the use boost ?'. Old gcc versions will work fine. Perhaps you can use an older version of boost as well – sehe Apr 03 '17 at 05:37
  • May be I should be more precise :). It's a legacy syste,, and there is no way to change the build environment or dependencies. – user3291059 Apr 03 '17 at 11:05
  • I don't think that's relevant. Just decide whether the answer answers the question (it does) and whether you found it helpful. If you had another question, you will have to post one. – sehe Apr 03 '17 at 12:33
2

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
sehe
  • 374,641
  • 47
  • 450
  • 633