How can I return char array with boost::optional

1.3k views Asked by At

I try to return simple array with boost::optional

boost::optional<const char *> foo () {
   char ar[100] = {};
   return boost::make_optional(true, ar);
}

and I got the following error:

could not convert ‘boost::make_optional(bool, const T&) [with T = char [100]](ar)’ from ‘boost::optional<char [100]>’ to ‘boost::optional<const char*>’ return boost::make_optional(true, ar);

How can I handle such confusion?

2

There are 2 answers

0
Denis Kotov On BEST ANSWER

boost::make_optional deduced ar as char [100] type, but it expected const char *. By default implicit casting is not happened in template parameter deduction.

If you want to use raw pointer, it is possible to use the following solution:

boost::optional<const char *> foo () {
    char ar[100] = {};
    return boost::make_optional(true, static_cast<const char *>(ar));
}

But in this case you lose information how many elements located in this array and maybe better to use in foo() function std::vector or std::array as in example of sehe

Good luck !!

0
sehe On

Closest you can do is by using a wrapper with value semantics.

That wrapper is std::array:

boost::optional<std::array<char, 100> > foo () {
   std::array<char, 100> ar {};
   return boost::make_optional(true, ar);
}

About arrays vs. pointers: