Skip to content

Instantly share code, notes, and snippets.

@Jerror
Created June 6, 2018 01:01
Show Gist options
  • Save Jerror/9d5d9a5b1c0cf4e78adc563d0088a5bf to your computer and use it in GitHub Desktop.
Save Jerror/9d5d9a5b1c0cf4e78adc563d0088a5bf to your computer and use it in GitHub Desktop.
Simple optional chaining
#include <cstring>
#include <optional>
using namespace std;
const int A = 4;
const int B = 6;
const int CD = 8;
const int E = 6;
optional<int> fa(int a)
{
if (a >= A) {
return a/2;
} else {
return nullopt;
}
}
optional<int> fb(int b)
{
if (b >= B) {
return b/3;
} else {
return nullopt;
}
}
optional<int> fcd(int c, int d)
{
if (c*d >= CD) {
return c*d/2;
} else {
return nullopt;
}
}
optional<int> fe(int e)
{
if (e >= E) {
return e;
} else {
return nullopt;
}
}
int main(int argc, char *argv[])
{
int a = atoi(argv[1]);
int b = atoi(argv[2]);
if (optional<int> tmp, x;
(tmp = fa(a)) && (x = fb(b)) && (x = fcd(*tmp, *x)) && (x = fe(*x)))
{
return *x;
} else {
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment