Reputation: 17253
I wanted to know if its possible to return a function that could either return a boolean or a void ? I know I could use std::optional
however that is available only in C++17 and my code base is C++11. I would like something like this
xxx process(int a)
{
if (a==1)
return true;
if (a==2)
return false;
if (a==3)
.... //return nothing
}
Upvotes: 0
Views: 62
Reputation: 1219
If you don't want to write an equivalent of std::optional yourself use an enum.
enum class Result
{
False,
True,
Nothing // or whatever name makes sense in your use case
};
Upvotes: 0
Reputation: 127
A variant might be a better match:
According to your requirement: a function that could either return a boolean or a void
See at: http://en.cppreference.com/w/cpp/utility/variant
The class template std::variant represents a type-safe union. An instance of std::variant at any given time either holds a value of one of its alternative types, or it holds no value (this state is hard to achieve, see valueless_by_exception).
Upvotes: 1
Reputation: 2353
For returning two values I use a std::pair (usually typedef'd). In C++11 and newer, you should use std::tuple for more than two return results.
The abstract example using the tuple
std::tuple<bool, int> process(int a)
{
if (a==1)
return std::make_tuple(true, 0);
if (a==2)
return std::make_tuple(false, 0);
if (a==3)
return std::make_tuple(false, 1);
}
Upvotes: 2