Home > Net >  how to define functor as third template class of map?
how to define functor as third template class of map?

Time:03-09

I am trying to define a map::key_comparator type, but I have no idea how to write the class type of functor std::less and std::greater.

// not compilable
using MapTree = std::map<int, string, std::map::key_compare >;
void funct(MapTree& a) {
a.push_back({1, "a"});
a.push_back({3, "d"});
a.push_back({10, "b"});
};

// usage
std::map<int, string, std::less<int>> s;
funct(s); // should produce s sorted in order of less

std::map<int, string, std::greater<int>> c;
funct(c); // should produce c sorted in order of greater

CodePudding user response:

You can simply make funct a function template:

template<class Map>
void funct(Map& a) {
    a[1] = "a";
    a[3] = "d";
    a[10] = "b";
}

CodePudding user response:

You need to make it a template; different std::map instantiations are distinct types.

If you want specific key and value types, use a partial specialization.

template<typename Order>
using MapTree = std::map<int, string, Order>;

template<typename Order>
void funct(MapTree<Order>& a) {
// ...
  •  Tags:  
  • c
  • Related