C++ 函数指针导致的函数重载
有一个关于重载函数的问题。请看以下代码:C++ 函数指针导致的函数重载,c++,function-pointers,overloading,C++,Function Pointers,Overloading,有一个关于重载函数的问题。请看以下代码: #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)(
#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 fv(int){}
void fc(const int){}
void fvr(int&){}
void fcr(常量int&){}
无效fm(无效(*fun)(常数int))
{
std::cout是的,顶级常量将被删除。来自gcc的错误
重新定义“无效格式(无效(*)(国际))”
正如你所看到的,const被删除了
引用N3376 8.3.5/5
生成参数类型列表后,任何顶级
形成参数类型时,将删除修改参数类型的cv限定符
函数类型
是的,您不能基于非指针/非引用参数的常量重载函数,请参阅:
这反过来又意味着指向函数的指针按值接受参数和常量值是同一类型的。为什么它为值而丢弃,而不是为引用而丢弃?@brachistochron只是因为引用中的常量不是顶级常量。是的,请获取它,谢谢。但如果比较函数参数,仍然无法获取它为何以这种方式工作=)>T*
和T const*
或T&
和T const&
,你会发现它有很大的区别。如果你比较T
和T const
,也有区别,但差别很小,调用方看不到,因此标准只是说它没有不同的函数签名。Simi大体上,T*
和T*const
没有什么区别。请注意,T&
和T&const
无法比较,因为后者根本不存在。