search

Home  >  Q&A  >  body text

c++ - 重载二义性问题

void f(void*)
{
    cout << 1;
}

void f(int)
{
    cout << 2;
}

int main()
{
    
    f(0);

    return 0;
}

上述代码在C++编译器中是否会报二义性,我的vs2015没有,是不是跟编译器有关?

PHPzPHPz2804 days ago870

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-17 15:39:14

    For function call statements, function matching will be sought at compile time. Function matching has three results: best match, no match, and ambiguous match.

    In the above code, f(0) will find the best match f(int), and you will not see the ambiguous matching error.

    Under gcc, f(NULL) will report an ambiguous matching error. Because NULL is defined as __null, its path to void* is as long as the path to int, so it is considered ambiguous. Sexual matching, NULL under Windows is directly 0, so no error will be reported. This will cause particularly strange phenomena when the template is reloaded, such as

    template<class F, class A>
    void test(F f, A a)
    {
        f(a);
    }
    void f(void*)
    {
        cout << 1;
    }
    test(f, NULL); //这里会报无匹配

    Since the best match of f(0) is f(int), if you define the f(int) function and also define the overloaded function f(void), then call f(void) The correct approach is f(nullptr), nullptr is specially used by c++11 to solve this problem.

    reply
    0
  • Cancelreply