Question

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.

Was it helpful?

Solution

Something like this:

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

OTHER TIPS

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)
    {

    }
}

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top