Search code examples
c++11boostboost-optional

How can I return char array with boost::optional


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?


Solution

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