Default initialized boost :: optional

Is there a default way to initialize the boost :: optional variable without providing a T name?

struct MyStruct
{
    int a;
};

int main(){
    boost::optional<MyStruct> opt;
    opt = MyStruct(); // <--
}

My goal is to omit the provision of the structure name when I just want to initialize default.

+4
source share
2 answers

If your compiler supports variable templates, and you are using Boost version 1.56 or higher, use emplace()without arguments:

opt.emplace();

If any of the conditions is not satisfied (either a compiler without variational patterns, or a senior Boost), use in_placefactory without arguments:

opt = boost::in_place();

in Boost 1.59, you can call a 0 argument emplace()even in C ++ 03 compilers.

+6

in-place factory,

#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>

struct Foo
{
    Foo() {}
    int bar = 5;  
};

int
main()
{
    boost::optional<Foo> foo;
    assert(!foo);
    foo = boost::in_place();
    assert(foo);
}

.

+2

All Articles