Jump to content
  • Advertisement
Sign in to follow this  
BaneTrapper

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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement

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 this post


Link to post
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 this post


Link to post
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

http://stackoverflow.com/questions/16227391/please-explain-this-code-that-uses-stdignore

// 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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!