Public Group

# c++ default argument issue

This topic is 2206 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello.

If i have a function and it has two parameters that have defined default value, is there a way to not pass a value for first parameter and pass a parameter for other.

void Func(int num = 1, int num2 = 2);
{
}

int main()
{
Func(void, 99); // as in i want the first parameter to use the default one
return 0;
}


##### Share on other sites

Nope, you can't do it like that. If you specify a parameter, you must also specify all parameters before it. The only parameters you can omit are the default ones after it.

Thank you on fast replay!

##### Share on other sites

I'm not quite sure, but couldn't this be done with std::bind?

Not with default parameters itself, but you could just bind the first parameter being the default value of Func (making it a 1-parameter function) and call it with whatever you need to as the second parameter.

Edited by weeska

##### Share on other sites

Or you could just write another function void OtherFunc(int num2) { Func(1, num2); }

##### Share on other sites

Or you could just write another function void OtherFunc(int num2) { Func(1, num2); }

One can go this way and use std::ignore together with overloading to keep the same name, "Func":

http://en.cppreference.com/w/cpp/utility/tuple/ignore

// this is abusing notation somewhat, since std::ignore is intended to be used with std::tie and std::tuple -- but, hey, it still does what it says, i.e., ignores stuff ;-)

For example: http://ideone.com/N8k05D

Note that it introduced additional maintenance costs -- previously, you only had default argument "1" in one place, now it's in two. Of course, you can still solve that (e.g., introducing a namespaced variable for the default argument), but that's still additional work to do. Overall, I'd probably avoid this.

#include <iostream>
#include <tuple>

void Func(int num = 1, int num2 = 2)
{
std::cout << num << '\n';
std::cout << num2 << '\n';
}

void Func(decltype(std::ignore), int num2 = 2)
{
Func(1, num2);
}

int main()
{
Func(std::ignore, 99); // as in i want the first parameter to use the default one
return 0;
}


Edited by Matt-D

• 18
• 29
• 11
• 23
• 16