Weird compiler error: Cannot convert parameter from 'int' to 'int &&'

前端 未结 4 1528
忘了有多久
忘了有多久 2020-12-09 04:14

What on earth is going on here?
I\'m trying to create a pair of an int and a string and I can create the pair if I use \"magic values\" but can

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-09 04:47

    make_pair does not make a pair of type pair, but rather deduces a suitable pair of reference types from its arguments to allow perfect forwarding. It's specified as

    template 
    pair make_pair(T1&& x, T2&& y);
    

    for some suitable reference types V1 and V2. This only works if the argument types are deduced, so that && can decay to an lvalue reference if necessary. By specifying the template parameters explicitly, they are no longer deduced, and so the function arguments can only be rvalues.

    The solution is to let the compiler deduce the types:

    num_text.push_back(std::make_pair(42, std::string("Smeg")));  // Works fine
    num_text.push_back(std::make_pair(42, text));                 // Works fine
    num_text.push_back(std::make_pair(num, std::string("Smeg"))); // Works fine
    num_text.push_back(std::make_pair(num, text));                // Works fine
    num_text.push_back(std::make_pair(42, std::string("Smeg")));  // Works fine again
    

    If you need to make a pair of a particular type, don't use make_pair, just make a pair

    // Works, but perhaps with more copying than you want.
    num_text.push_back(std::pair(num, text));   
    

提交回复
热议问题