简体   繁体   中英

use of std::less in std::map does not compile

I am unable to understand why does following function not compile

#include <iostream>
#include <map>

int main(){
  std::map<int, int, std::less<int>> myMap(std::less<int>());
  myMap[2] = 2;
  std::cout << myMap[2] << std::endl;
  return 0;
}

The error message is as follows -

std_less_check.cpp: In function ‘int main()’:
std_less_check.cpp:6:10: warning: pointer to a function used in arithmetic [-Wpointer-arith]
   myMap[2] = 2;
          ^
std_less_check.cpp:6:14: error: assignment of read-only location ‘*(myMap + 2)’
   myMap[2] = 2;
              ^
std_less_check.cpp:6:14: error: cannot convert ‘int’ to ‘std::map<int, int, std::less<int> >(std::less<int> (*)())’ in assignment
std_less_check.cpp:7:23: warning: pointer to a function used in arithmetic [-Wpointer-arith]
   std::cout << myMap[2] << std::endl;

while following compiles successfully

#include <iostream>
#include <map>

int main(){
  std::map<int, int, std::less<int>> myMap(std::less<int>{});
  myMap[2] = 2;
  std::cout << myMap[2] << std::endl;
  return 0;
}

Could someone please help me with this?

In the first program, you have a vexing parse. If the compiler can parse a declaration as either a variable or a function, it will choose to parse it as a function.

myMap can be parsed as a function declaration.

It returns a std::map<int, int, std::less<int>> .

It takes an argument of type std::less<int>() , which is itself a function type that returns a std::less<int> and takes no arguments. Note that you can't actually have a function type as an argument; the type is actually a pointer to a function that takes no arguments and returns a std::less<int> .


In the second program, replacing () with {} resolves the ambiguity. Now myMap can no longer be a function declaration, and so it instead declares a variable of type std::map<int, int, std::less<int>> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM