I've been wondering: since exceptions can be of any type, would they be viable for returning a different type depending on the conditions?
I know it's not very clear so I'll make an example: for a messaging app, we want the users to be able to send their position, but for privacy reasons, we want it to only be shown if the user is online:
void get_user_position(User& u) {
if(!u.is_online()) throw false;
else throw u.get_position();
}
void send_user_position(User& u) {
try {
get_user_position(u);
} catch(bool e) {
//send a message like "user isn't online"
} catch(user_position e) {
//send the position
}
}
This would avoid the need for -1
s as failed operation flags and stuff like that. Thoughts? Opinions? Am I completely missing something?
Exceptions should be used for exceptions and not for normal conditional code parts. If "not online" is now an exception is matter of taste.
But if your question is more general and asks about giving back different return types from a single function you should think of using std::variant. With std::holds_alternative you can ask which type was stored in the variant. There are several methods to deal with the content of variants e.g. std::visit
struct A{};
struct B{};
std::variant < A,B > Func( int x)
{
if ( x == 0 ) return A{};
return B{};
}
int main()
{
auto v = Func( 0 );
if ( std::holds_alternative<A>(v) )
{
std::cout << "A" << std::endl;
}
else if ( std::holds_alternative<B>(v) )
{
std::cout << "B" << std::endl;
}
// or even use std::visit or whatever is helpful...
}