Search code examples
c++expressionemplace

"expression cannot be used as a function" in return statement


Code (also screenshot):

/***
Attempts to emplace new_vert in vertices,
    returning false
        if it failed (i.e., the vertex was already in vertices)
    or true
        if it succeeded
***/
template <typename T>
bool Graph<T>::addVert(const T& new_vert) {
    return vertices.emplace(std::piecewise_construct,
        std::forward_as_tuple(new_vert),
        std::forward_as_tuple()).second();
};

As the screenshot shows, the error occurs on the last parenthesis of ".second()".

vertices is of type std::map<T, std::set<T>>, and emplace() should return a pair<iterator,bool>, with the bool accessible via second(), hence returning it. Different versions of the code (e.g., catching the pair with a variable foo and returning foo.second()) makes no difference; the error follows the last parenthesis of second().

Looking at other questions with this error, they seem to boil down to operators missing somewhere, but that doesn't seem to be the case here. Why is it happening?


Solution

  • The second member of std::pair is a member variable, not a member function. You just need to omit the parentheses, as you're getting its value (as opposed to calling it):

    return vertices.emplace(std::piecewise_construct,
        std::forward_as_tuple(new_vert),
        std::forward_as_tuple()).second;