通过函数指针重载函数

Function overloading by function pointer

有一个关于重载函数的问题。看这段代码:

#include<iostream>

void fv(int){}
void fc(const int){}
void fvr(int&){}
void fcr(const int&){}

void fm(void(*fun)(const int))
{
    std::cout << "Constant called" << std::endl;
}

//void fm(void(*fun)(int))
//{
//  std::cout << "non Constant called" << std::endl;
//}

void fm(void(*fun)(const int&))
{
    std::cout << "Constant ref called" << std::endl;
}

void fm(void(*fun)(int&))
{
    std::cout << "non Constant ref called" << std::endl;
}

int main()
{
    fm(&fc);
    fm(&fv);
    fm(&fvr);
    fm(&fcr);
    return 0;
}

如果您取消注释 void fm(void(*fun)(int)) 函数,您会发现编译器无法通过按值接受参数的函数指针和接受 const 值的函数指针静态重载函数。此外,如果您取消注释 void(*fun)(const int) 并注释 void(*fun)(const int) 那么所有编译都会成功。但是,如果我们使用引用,它可以编译。不明白为什么,你能解释一下吗?这是否意味着指向按值接受参数和按常量值接受参数的函数的指针是相同类型?

更新: Top-level const doesn't influence a function signature 有一个很好的解释为什么应该删除顶级 const。

是的,顶级常量将被删除。来自 gcc

的错误

redefinition of ‘void fm(void (*)(int))’

如您所见,const 已被删除。

引自 N3376 8.3.5/5

After producing the list of parameter types, any top-level cv-qualifiers modifying a parameter type are deleted when forming the function type.

是的,您不能基于非指针/非引用参数的常量重载函数,请参阅: Functions with const arguments and Overloading

这反过来意味着指向按值接受参数的函数指针和 const 值是同一类型。