1

Take the following example code:

typedef std::vector<uint8_t> uint8Vect_t;

void setSomeThing(int value, uint8Vect parameters)
{
    //... do some stuff ...
    if (parameters.size() > 0)
    {
        //... do some stuff with parameters ...
    }
}

int main(void)
{
    uint8Vect intParams;
    intParams.push_back(1);
    intParams.push_back(2);

    // Case 1 - pass parameters
    setSomeThing(1, intParams);

    // Case 2 - pass no parameters, default value should be used
    setSomeThing(1);

    return 0;
}

My question here is that I want to set a default value for the vector parameter of the function like this:

setSomeThing(int value, uint8Vect parameters = 0)

Where if no parameter "parameters" is passed in then an empty vector is used by default. However I can't figure out what the syntax should be - if it is possible. I know I could use an overloaded function, but I want to know how to do this anyway.

code_fodder
  • 15,263
  • 17
  • 90
  • 167

3 Answers3

4

Calling the default constructor will construct an empty vector.

#include <vector>
typedef std::vector<uint8_t> uint8Vect_t;
void setSomeThing(int value, uint8Vect_t parameters = uint8Vect_t{})
{
    if (parameters.size() > 0)
    {

    }
}
  • This method is better because you can create a custom default vector wit any values you want. But it requires C++11 – Davidbrcz Jan 13 '14 at 12:54
  • Thanks very much. Yes I was going to say this works fine for c++11, but not c99 - I did not specify which I was using though :) – code_fodder Jan 13 '14 at 12:57
  • @Davidbrcz It is not necessarily "better". Creating a custom size 500 vector with values set to 42 would be quite tedious. – juanchopanza Jan 13 '14 at 12:58
  • @Davidbrcz The only difference between mine and juanchopanza's answer is that I fixed some of the typos on op's code. –  Jan 13 '14 at 12:58
  • 3
    If using C++11, even `uint8Vect_t parameters = {}` works the same way. – chris Jan 13 '14 at 12:59
  • @remyabel hang on.... what typos, I am not spotting them :( (EDIT: Actually I think I found it....the missing brackets, sorry). – code_fodder Jan 13 '14 at 13:07
  • @chris keep in mind using `={}` [may be broken is you are using Visual Studio](http://stackoverflow.com/questions/21044488/known-compiler-bug-in-vc12/21048459#21048459). – Shafik Yaghmour Jan 13 '14 at 13:12
  • @ShafikYaghmour, That's a shame. – chris Jan 13 '14 at 13:25
  • @ShafikYaghmour - ya, I totally do! - I am always switching between c and c++ and I get very confused sometimes! – code_fodder Jan 13 '14 at 15:00
3

Something like this:

void setSomeThing(int value, uint8Vect_t parameters = uint8Vect_t()) { .... }
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

If using C++11, even uint8Vect_t parameters = {} works - comment by chris