我正在使用一个函数返回std::pair:
std::pair<bool, int> myFunction() {
//Do something...
if (success) {
return {true, someValue};
}
else {
return {false, someOtherValue};
}
}
Run Code Online (Sandbox Code Playgroud)
一旦成功,该对的第一个值将是true,否则false.
一些函数调用myFunction()使用返回的对的第二个值,而其他函数则不使用.对于那些人,我这样称呼myFunction():
bool myOtherFunction() {
//Do something...
bool success;
std::tie(success, std::ignore) = myFunction(); //I don't care about the pair's second value
return success;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法避免直接声明bool success和返回myFunction()返回值的第一个元素?
a std::pair只是一个包含2个值的结构; 所以只返回结构中的"第一个"项.
return myFunction().first;
Run Code Online (Sandbox Code Playgroud)
也许
return std::get<0>(myFunction());
Run Code Online (Sandbox Code Playgroud)
要么
return std::get<bool>(myFunction());
Run Code Online (Sandbox Code Playgroud)