Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 788
atuly Avatar asked Mar 02 '23 18:03

atuly


1 Answers

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>>.

like image 199
cigien Avatar answered Mar 27 '23 18:03

cigien