Skip to content

Instantly share code, notes, and snippets.

@RadAd
Created September 24, 2024 00:06
Show Gist options
  • Save RadAd/c23a10778a0381bba53dced414adbeee to your computer and use it in GitHub Desktop.
Save RadAd/c23a10778a0381bba53dced414adbeee to your computer and use it in GitHub Desktop.
#include <cstdio>
#include <optional>
#include <memory>
#include <set>
std::optional<int> foo()
{
return {};
}
std::unique_ptr<int> bar()
{
return {};
}
std::set<int> coo()
{
return {};
}
template <class T>
class or_else
{
public:
or_else(const T& x)
: m_x(x)
{
}
const T& value() const { return m_x; }
private:
T m_x;
};
template <class T, class U>
class find_or_else
{
public:
find_or_else(const T& x, const U& y)
: m_x(x), m_y(y)
{
}
const T& find() const { return m_x; }
const U& value() const { return m_y; }
private:
T m_x;
U m_y;
};
template <class T>
const T& or_else_f(const std::optional<T>& o, const or_else<T>& e)
{
return o ? o.value() : e.value();
}
template <class T>
const T& or_else_f(const std::unique_ptr<T>& o, const or_else<T>& e)
{
return o ? *o.get() : e.value();
}
template <class T, class U, class V>
const T& find_or_else_f(const std::set<T>& o, const find_or_else<U, V>& e)
{
auto it = o.find(e.find());
return it != o.end() ? *it : e.value();
}
template <class T, class U>
auto operator|(const T& o, const or_else<U>& e)
{
return or_else_f(o, e);
}
template <class T, class U, class V>
auto operator|(const T& o, const find_or_else<U, V>& e)
{
return find_or_else_f(o, e);
}
int main()
{
auto a = foo() | or_else(3);
auto b = bar() | or_else(5);
auto c = coo() | find_or_else(2, 7);
printf("out a %d\n", a);
printf("out b %d\n", b);
printf("out c %d\n", c);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment