Alexander210
Alexander210

Reputation: 11

std::map<std::any, std::any> trouble

I'm trying to make an std:map with std::any types of keys and values

Visual Studio 2017

std::map<std::any, std::any> m("lastname", "Ivanov");
std::cout << std::any_cast<std::string>(m["lastname"]) << std::endl;

getting me an

error: binary '<' : no operator found which takes a left-hand operand of type 'const_Ty'

Upvotes: 1

Views: 1225

Answers (1)

darune
darune

Reputation: 10962

std::any doesn't have binary '<' operater (less than). The default method of how to 'index' the std::map elements.

Solutions could include:

  1. Use another key (that has operator '<')
  2. Use a custom comparator, for example:

    #include <map>
    #include <any>
    
    int main() {
        auto elements = std::initializer_list<std::pair<const std::any, std::any>>{};
        auto mymap = std::map(elements, [](const std::any& lhs, const std::any& rhs){return false;});
    }
    

Then implement the compare function instead of returning false.

try it yourself

Upvotes: 1

Related Questions