Search code examples
c++vectordefault-value

How can you give a default value for a vector parameter in a function


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.


Solution

  • Something like this:

    void setSomeThing(int value, uint8Vect_t parameters = uint8Vect_t()) { .... }