hg_git hg_git - 1 month ago 13
C++ Question

type of pair that unordered map emplace returns

I've a function which is calling

emplace()
method on an std unordered map container and I need to return the exact return value as given by
emplace()
call. I know it returns a
std::pair
of an iterator(whether new or old depends on successful operation) and a bool representing success. Earlier I was returning only the bool part like this:

auto result = map.emplace(std::make_pair(id, someObj));
return result.second;


and I knew return type was
bool
. But now I need to return the original
result
variable but I don't know it's type so what should I put in the function prototype in its class?

I tried using
typeid
method on iterator but it gave:

St4pairINSt8__detail14_Node_iteratorIS_IKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES7_ELb0ELb1EEEbE


as output.

Answer

You can use C++11's trailing return type and decltype to accomplish this. Doing that we would have a function like

auto some_function(some_parameters) -> decltype(map.emplace(id, someObj))
{
    return map.emplace(id, someObj);
}

Now the compiler will deduce the return type to be exactly the return of the emplace call.

If you can use C++14 or newer then you can use the auto return type deduction and simplify the code to

auto some_function(some_parameters)
{
    return map.emplace(id, someObj);
}

Here the compiler will deduce the return type of the function to the the type returned from the function by the return statement. Do note that you cannot return different types in the function body this way as the compiler would not be able to deduce which type to use.


Note that in the above examples I did not use std::make_pair with emplace. Unlike insert which expects a pair you can directly construct in emplace.