#include <map>
#include <vector>
void foo(std::pair<int, int>& p)
{}
int main()
{
std::pair<int, int> p{1,2};
foo(p);
std::vector<std::pair<int, int>> v{{1,2}};
for (auto& element : v)
{
foo(element); // works fine
}
std::map<int, int> m{std::make_pair(1,2)};
//std::map<int, int> m2{{1,2}};
for (auto& element : m) // the problematic loop
{
foo(element);
}
return 0;
}
I2luY2x1ZGUgPG1hcD4KI2luY2x1ZGUgPHZlY3Rvcj4KCnZvaWQgZm9vKHN0ZDo6cGFpcjxpbnQsIGludD4mIHApCnt9CgppbnQgbWFpbigpCnsKICAgIHN0ZDo6cGFpcjxpbnQsIGludD4gcHsxLDJ9OwogICAgZm9vKHApOwogICAgc3RkOjp2ZWN0b3I8c3RkOjpwYWlyPGludCwgaW50Pj4gdnt7MSwyfX07CiAgICBmb3IgKGF1dG8mIGVsZW1lbnQgOiB2KQogICAgewogICAgICAgIGZvbyhlbGVtZW50KTsgIC8vIHdvcmtzIGZpbmUKICAgIH0KCiAgICBzdGQ6Om1hcDxpbnQsIGludD4gbXtzdGQ6Om1ha2VfcGFpcigxLDIpfTsKICAgIC8vc3RkOjptYXA8aW50LCBpbnQ+IG0ye3sxLDJ9fTsKICAgIGZvciAoYXV0byYgZWxlbWVudCA6IG0pICAvLyB0aGUgcHJvYmxlbWF0aWMgbG9vcAogICAgewogICAgICAgIGZvbyhlbGVtZW50KTsKICAgIH0KCiAgICByZXR1cm4gMDsKfQ==
prog.cpp: In function ‘int main()’:
prog.cpp:21:13: error: invalid initialization of non-const reference of type ‘std::pair<int, int>&’ from an rvalue of type ‘std::pair<int, int>’
foo(element);
^~~~~~~
In file included from /usr/include/c++/6/bits/stl_algobase.h:64:0,
from /usr/include/c++/6/bits/stl_tree.h:63,
from /usr/include/c++/6/map:60,
from prog.cpp:1:
/usr/include/c++/6/bits/stl_pair.h:272:19: note: after user-defined conversion: constexpr std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&) [with _U1 = const int; _U2 = int; typename std::enable_if<(std::_PCC<((! std::is_same<_T1, _U1>::value) || (! std::is_same<_T2, _U2>::value)), _T1, _T2>::_ConstructiblePair<_U1, _U2>() && std::_PCC<((! std::is_same<_T1, _U1>::value) || (! std::is_same<_T2, _U2>::value)), _T1, _T2>::_ImplicitlyConvertiblePair<_U1, _U2>()), bool>::type <anonymous> = 1u; _T1 = int; _T2 = int]
constexpr pair(const pair<_U1, _U2>& __p)
^~~~
prog.cpp:4:6: note: initializing argument 1 of ‘void foo(std::pair<int, int>&)’
void foo(std::pair<int, int>& p)
^~~