hg_git hg_git - 1 year ago 109
C++ Question

type of pair that unordered map emplace returns

I've a function which is calling

method on an std unordered map container and I need to return the exact return value as given by
call. I know it returns a
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
. But now I need to return the original
variable but I don't know it's type so what should I put in the function prototype in its class?

I tried using
method on iterator but it gave:


as output.

Answer Source

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.