微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 函数指针的函数重载

一个关于重载函数的问题.看看这段代码
#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),那么所有编译都是成功的.但是,如果我们使用引用它编译好.不明白为什么,你能解释一下吗?这是否意味着通过值和const值接受参数的函数指针是相同的类型?

UPD:
Top-level const doesn’t influence a function signature
一个很好的解释为什么应该删除顶级const.

解决方法

是的,顶级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.

原文地址:https://www.jb51.cc/c/118643.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐