67 ms·
Proof of concept: #include <optional> #include <functional> #include <type_traits> using std::optional; using std::conditional_t; using std:
by kazinator 5y ago
Proof of concept:
#include <optional>
#include <functional>
#include <type_traits>
using std::optional;
using std::conditional_t;
using std::reference_wrapper;
using std::cout;
using std::endl;
template <typename T>
class optref {
T *ptr;
public:
optref<T>() : ptr(nullptr) { }
optref<T>(T &obj) : ptr(&obj) { }
optref<T> &operator =(const T &rhs)
{
if (!ptr)
throw 42;
*ptr = rhs;
return *this;
}
};
template <bool ref, typename T>
using opt = conditional_t<ref, optref<T>, optional<T>>;
int main()
{
int x = 42;
opt<true, int> rox = x;
rox = 3;
cout << x << endl;
}
Compiles with GNU g++ -std=c++17 -Wall -W -pedantic.
The output is
3
showing that rox is a reference to x. Via the hacky assignment operator I threw in for this purpose.
We can build abstractions on opt<ref, T> but they have to carry that pesky parameter. If we can move it to the right and default it to false, that helps if most of our optionals aren't references.
It's not obvious how to get rid of it.