Home > database >  Make a function has higher precedence than another
Make a function has higher precedence than another

Time:09-24

So I have a function:

void foo(char a = 'A', int b = 0)
{
    // code
}

And I have another one:

void foo(int b = 0, char a = 'A')
{
    //code
}

Then if I call foo(), it will return an error because the compiler can't decide which function to call. So can I make a function that has higher precedence than another? So if I call foo() then the compiler which one to choose?

CodePudding user response:

You probably want to use function overloading here:

void foo(char a, int b = 0)
{
    // code
}

void foo(int b, char a = 'A')
{
    //code
}

void foo()
{
    foo(0); // Or 'foo('A');', depends on which overload you want to give priority
}

Edit: Or you could just remove the first default argument from one of the overloads:

// Makes the compiler select the first overload when doing 'foo()'
void foo(char a = 'A', int b = 0)
{
    // code
}

void foo(int b, char a = 'A')
{
    //code
}

Or:

// Makes the compiler select the second overload when doing 'foo()'
void foo(char a, int b = 0)
{
    // code
}

void foo(int b = 0, char a = 'A')
{
    //code
}

CodePudding user response:

There is no way to apply an implicit preference for one function or the other if both are found to be equally viable during overload resolution.

If you're stuck in this situation, the best you could do would be to wrap both functions in separate namespaces so you could choose which one to access through namespace qualified references. Other parts of the code could still bring both into their own lookup realm for unqualified use with using statements, and as long as the calls were unambiguous, they could be used unqualified in that way, with the programmer falling back to explicit namespace qualification when there is no way to resolve the ambiguity.

  • Related