Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default initialized boost::optional

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

struct MyStruct
{
    int a;
};

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

My goal is to omit providing struct name when I just want to default initialize opt.

like image 368
user2551229 Avatar asked Feb 10 '23 23:02

user2551229


2 Answers

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

opt.emplace();

If either of the conditions is not met (either a compiler without variadic templates or an older Boost) use in_place factory with no arguments:

opt = boost::in_place();

in Boost 1.59 you will be able to call 0-argument emplace() even in C++03 compilers.

like image 157
Andrzej Avatar answered Feb 13 '23 13:02

Andrzej


You can use an in-place factory if you'd like to default initialize an optional value

#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);
}

live demo here.

like image 33
Sam Miller Avatar answered Feb 13 '23 12:02

Sam Miller