Skip to content

Instantly share code, notes, and snippets.

@avikivity
Created June 7, 2025 21:03
Show Gist options
  • Save avikivity/b22aba5684edd09a5842df18b1954870 to your computer and use it in GitHub Desktop.
Save avikivity/b22aba5684edd09a5842df18b1954870 to your computer and use it in GitHub Desktop.
#include <optional>
#include <string>
#include <random>
#include <ranges>
#include <functional>
using namespace std::literals::string_literals;
template <typename T>
class avi_optional {
bool _engaged = false;
T _value;
public:
avi_optional(std::nullopt_t) : _engaged(false), _value() {}
avi_optional(T&& in) : _engaged(true), _value(std::move(in)) {}
};
template <template <typename T> class Optional>
void
run_test() {
auto gen_bool = std::bind(std::uniform_int_distribution<>(0, 1),
std::default_random_engine());
using opt_string = Optional<std::string>;
auto v_ref
= std::views::iota(0, 10000)
| std::views::transform([&] (auto ignore) {
return gen_bool() ? opt_string(std::nullopt) : opt_string("xyz");
})
| std::ranges::to<std::vector>();
for (unsigned i = 0; i < 1000000; ++i) {
auto v_copy = v_ref;
}
}
int main(int ac, char** av) {
if (ac >= 2 && av[1] == "a"s) {
run_test<avi_optional>();
} else {
run_test<std::optional>();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment