samedi 25 novembre 2023

How to make a zero-cost `std::optional`-like class to wrap functions returning value availability

I can call some function which I don't control (external API):

extern bool get_val(int *val) noexcept;

get_val() either sets *val and returns true, or doesn't set *val and returns false.

Is there any way to wrap get_val() such as to return an std::optional-like object instead:

my_optional<int> get_val() noexcept;

while reaching no overhead?

In other words, the two usages below must generate the same/similar instructions:

int v;

if (get_val(&v)) {
    // use `v`
}
if (const auto opt_val = get_val()) {
    // use `*opt_val`
}

Aucun commentaire:

Enregistrer un commentaire