Domanda

Maybe I'm being stupid, but I don't see what the problem with this code is. I'm starting to resort to doubting my tools. I'm using Clang (C++11), and its libc++. If it's my fault, I apologise and thank in advance whoever points out my stupidity, but if it's not, maybe this is a deeper issue..

std::map<int, bool> map_;

map_.insert(std::make_pair<int, bool>(5, true)); //Use a literal, compiles OK

int x = 5;
map_.insert(std::make_pair<int, bool>(x, true)); //Use a local of same type, compile error: 'no known conversion from 'int' to 'int &&' for 1st argument'
È stato utile?

Soluzione

std::make_pair takes a "universal reference" to its arguments. A universal reference can bind to pretty much anything. This is the actual signature:

template< class T1, class T2 >
constexpr std::pair<V1,V2> make_pair( T1&& t, T2&& u );
//                                    ^^^^^^^^^^^^^^

When you explicitly supply the type (unnecessarily I might add), it turns the function call into this:

... ( int&& t, bool&& u );

Meaning the arguments are no longer universal references but rvalue-references. Rvalue-references can only bind to rvalues, not lvalues, hence the error for the first argument.

The solution to this issue is to allow template argument deduction to do its job:

map_.insert(std::make_pair(x, true));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top