0

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?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Yuriy Gyerts
  • 1,464
  • 18
  • 30
  • 1
    Er, you *don't!* If you want to have a string then use `std::string`. If you want a run-time changeable vector then use `std::vector`. If you want an array with a size fixed at compile-time then use `std::array`. – Some programmer dude Aug 29 '17 at 16:02
  • As for your problem, arrays are not pointers, and pointers are not arrays. Read the error message again, and see what it deduces the type of `ar` to be. Then compare it to what you say the return type is. – Some programmer dude Aug 29 '17 at 16:03
  • But I know that name of array is a pointer to a first element of array. Strange... – Yuriy Gyerts Aug 29 '17 at 16:14
  • No, an array can *decay* to a pointer to its first element. But it *isn't* by itself a pointer. That is, you can decay `ar` to `&ar[0]`, but you can't use it when returning since that will return a pointer to a variable that cease to exist and will disappear directly once the function returns. – Some programmer dude Aug 29 '17 at 16:19
  • Thank you, now it's clear :) – Yuriy Gyerts Aug 29 '17 at 16:34

2 Answers2

3

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:

sehe
  • 374,641
  • 47
  • 450
  • 633
1

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 !!

Denis Kotov
  • 857
  • 2
  • 10
  • 29