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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With