Search code examples
c++functionc++11ambiguous

Make a function has higher precedence than another


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?


Solution

  • 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
    }