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>>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With