Tigran Sahakyan
Tigran Sahakyan

Reputation: 425

C++: How to initialize and call a method on std::optional?

Let's consider this code

std::optional<flat_set<int>> object;

void f(int v) {
    if (!object.has_value()) {
        object = flat_set<int>{};
    }
    object->insert(v);
}

How can I avoid if part? Is there any way to write the body of function in one line by calling one method?

Upvotes: 0

Views: 939

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69864

There isn't much you can do to avoid the if unless you absolutely know that the optional has a value (and if you know, why use an optional?)

You could wrap the conditional part into a lambda/function:

#include <optional>
#include <boost/container/flat_set.hpp>

std::optional<boost::container::flat_set<int> > objects;

void f(int _v) 
{
    auto assure = [&]() -> decltype(auto)
    {
        if (objects.has_value())
            return *objects;
        else
            return objects.emplace();
    };

    assure().insert(_v);
}

another way...

#include <optional>
#include <boost/container/flat_set.hpp>

std::optional<boost::container::flat_set<int> > objects;

template<class T> 
auto assure_contents(std::optional<T>& opt) -> T&
{
    if (opt.has_value())
        return *opt;
    else
        return opt.emplace();
}

void f(int _v) 
{
    assure_contents(objects).insert(_v);
}

Upvotes: 4

Related Questions