0

How to parse function arguments, when all have default values and only some of them are used? Example: I have a function with several arguments with default values

void fun(string a="", int b=0, string c="", int d=0)
{
 //parse used arguments somehow
}

I want to use it with different value of arguments, for example:

fun("foo", 10);
fun(10, 10);

How can I determine which arguments were used? Maximum value of arguments is known and order will be always the same. I do not want to run function like:

fun("", 3, "", 10);

And I cannot use variadic functions.

Any ideas?

4
  • 1
    "How can I determine which arguments were used?" You can't. I'm also fairly certain fun(10, 10); will either not compile as 10 is not a string, or will not do what you expect (it'll probably assume 10 is a pointer to a char*) Commented Nov 20, 2014 at 14:49
  • @Borgleader, Nah, it won't compile. std::string deliberately made sure of that. Commented Nov 20, 2014 at 14:50
  • 1
    @chris It will if you call with 0 instead like so foo(0, 10); which is a really nasty bug source in this case. Commented Nov 20, 2014 at 14:55
  • @Borgleader, For 0, yes. That's extremely unfortunate. Commented Nov 20, 2014 at 15:13

1 Answer 1

3

Overload the function.

void fun(int b, int d) { fun("", b, "", d); }

Then fun(3, 10) becomes equivalent to fun("", 3, "", 10).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.