Search code examples
c++overloadingoverload-resolution

Ranking of implicit conversion sequences [f(int) and f(const int&)]


Consider the following functions:

void f(int) {...}
void f(const int&) {...}

They are different and their definitions compile together successfully. But is there a way to call any of them when they both participate in overload resolution? And if there is no way, why are they not considered the same function like these two:

void g(int) {...}
void g(const int) {...} // error: redefinition of 'void g(int)'

Solution

  • If you want to explicitly call a particular function of an overload set you can cast the function to a function pointer with the signature yo want. That would look like

    void f(int) { std::cout << "void f(int) \n"; }
    void f(const int&) { std::cout << "void f(const int&)\n"; }
    
    int main () 
    {
        auto fi = static_cast<void(*)(int)>(f);
        auto fciref = static_cast<void(*)(const int&)>(f);
        fi(2);
        fciref(2);
    }
    

    which outputs

    void f(int) 
    void f(const int&)
    

    Otherwise you can't call your function as neither is better than the other according to the tie-break rules.