c++ - How to elegantly emplace optional with const values -


i trying use std::optional late instantiate object (which not valid before). found annoying situation, not know how elegantly solve this.

i have following data structure:

struct foo {     int foo1;     float foo2; }; 

as member std::optional<foo> foo_.

in function

void bar::bar(int const value1, float const value2) {     foo_.emplace(value1, value2); } 

to surprise, fails compile (in gcc 7.1) because tries call constructor of foo int const&, float const&. naive me tried specialize emplace as:

foo_.emplace<int, float>(value1, value2); 

which did not work either because tries use initializer_list then.

so question how 1 call emplace elegantly?

you have add constructor emplace use () constructor , not {} (which allow aggregate initialization).

struct foo {      foo(int i, float f) : foo1(i), foo2(f) {}      int foo1;     float foo2; }; 

or explicit on constructor used:

foo_.emplace(foo{value1, value2}); 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -