-2

I'm using a function that returns an std::pair:

std::pair<bool, int> myFunction() {
    //Do something...

    if (success) {
        return {true, someValue};
    }
    else {
        return {false, someOtherValue};
    }
}

On success, the pair's first value will be true, otherwise false.

Some functions that call myFunction() use the returned pair's second value, others don't. For those, I'm calling myFunction() like this:

bool myOtherFunction() {
    //Do something...

    bool success;
    std::tie(success, std::ignore) = myFunction(); //I don't care about the pair's second value

    return success;
}

Is there a way to avoid declaring bool success and returning myFunction()'s return value's first element directly?

Julini
  • 45
  • 1
  • 7
  • 6
    Did you try `return myFunction().first;` ? – Slava Mar 21 '18 at 17:22
  • 2
    Maybe you should look at the [documentation for `std::pair`](http://en.cppreference.com/w/cpp/utility/pair#Non-member_functions). – Arnav Borborah Mar 21 '18 at 17:25
  • @ArnavBorborah: Thanks. I did know `std::pair` members `first` and `second`, but somehow didn't think about using them on function call. – Julini Mar 21 '18 at 17:48

2 Answers2

10

a std::pair is just a struct with 2 values; so just return the "first" item in the struct.

return myFunction().first;
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
UKMonkey
  • 6,941
  • 3
  • 21
  • 30
  • ... of course! Now it seems obvious to me. Thank you, that works very fine for my use case. – Julini Mar 21 '18 at 17:40
6

Perhaps

return std::get<0>(myFunction());

or

return std::get<bool>(myFunction());
Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64