0

I have many calls to a function that takes just one argument and I don't want update those calls. But I want to call that function from some other special place but in that case it should additionally fill a vector that I will pass with some data.

I know I can create a default argument with NULL pointer to a std::vector container and then, if it is null, skip doing any extra actions and if it is a valid pointer - gather data to vector. However I wanted to try using boost::optional.

Please see the code below. It compiles and works, but Is this approach fine or I shouldn't do that and better use raw pointer?

#include <boost/optional.hpp>
#include <boost/none_t.hpp>
#include <vector>

//header file declaration
int doAction(
   int      value,
   char     *msg = NULL,
   boost::optional<std::vector<int>&> optionalNumberVec = boost::none);

//main.cpp
int doAction(int value, char* msg, boost::optional<std::vector<int>&> optionalNumberVec)
{
   //do main actions here
   //...
   //...
   //end of main action

   //get additional information to table
   if (optionalNumberVec)
   {
      optionalNumberVec.get().push_back(5);
      optionalNumberVec.get().push_back(3);
   }
   return 1;
}

int main()
{
   std::vector<int> numVec;
   boost::optional<std::vector<int>&> optionalNumberVec(numVec);
   doAction(2);
   doAction(2, NULL, optionalNumberVec);

   return 0;
}
Ramzi Khahil
  • 4,932
  • 4
  • 35
  • 69
user7242858
  • 81
  • 1
  • 9
  • http://codereview.stackexchange.com/ might be more appropriate. – Jarod42 Mar 16 '17 at 20:30
  • 1
    There is nothing wrong with passing a pointer in this instance, why complicate it? – keith Mar 16 '17 at 20:35
  • @Jarod42, Thank you, next time i will remember to post code reviews there. keith, because i have heard about boost::optional concept some time ago and if i don't use it so probably i will forget about it. And if i implement it in some function then I will remember about it when it will be more useful. – user7242858 Mar 16 '17 at 21:03

1 Answers1

0

Using boost or not is a simple decision based on your preferences (or your boss's preferences).

Once you get used to C++ you will notice that it doesn't really matter which one you use, as long you know how to use them.

Ramzi Khahil
  • 4,932
  • 4
  • 35
  • 69