ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

如何绑定重载函数

2021-11-22 10:36:41  阅读:206  来源: 互联网

标签:std shoot Function 函数 bind 绑定 重载


◆ 问题

环境:macOS Mojave (版本10.14.6), clang-1001.0.46.4 (-std=c++11)

代码中存在重载(overloaded)的自由函数(也称全局函数)或类成员函数,当开发者尝试用 std::bind 绑定其中一个时,会提示如下编译错误:

error: no matching function for call to 'bind'
std::bind
^~~~~~~~~

note: candidate template ignored: couldn't infer template argument '_Fp'
bind(_Fp&& \__f, _BoundArgs&&... \__bound_args)
^

note: candidate template ignored: couldn't infer template argument '_Rp'
bind(_Fp&& \__f, _BoundArgs&&... \__bound_args)
^

◆ 示例

有两个重载的 shoot 自由函数(#1,#2),两个重载的类成员函数 Archer::shoot(#3,#4),

void shoot() {    // #1
    std::printf("\n\t[Free Function] Let an arrow fly... Hit!\n");
}


bool shoot(unsigned n) {    // #2
    std::printf("\n\t[Free Function] Let %d arrows fly... All missed!\n", n);
    return false;
}


class Archer {
  public:
    void shoot() {    // #3
        std::printf("\n\t[Member Function] Let an arrow fly... Missed!\n");
    }
    bool shoot(unsigned n) {    // #4
        std::printf("\n\t[Member Function] Let %d arrows fly... All hit!\n", n);
        return true;
    }
};

开发者希望绑定一个自由函数(#2)或一个类成员函数(#4)时,

// bind #2
std::bind(shoot, 3)();

Archer hoyt;
// bind #4
std::bind(&Archer::shoot, &hoyt, 3)();

编译该代码时会抛出前述编译错误。

◆ 原因

重载函数的函数签名(signature)不同,是不同的函数。当开发者想绑定一个重载函数而仅给出名字时,编译器无法判定希望绑定的是哪一个函数,就会抛出编译错误。

◆ 解法

在绑定重载函数时,给出重载函数的签名。

方法一,把函数签名作为类型参数传给 std::bind 函数,

// std::bind<Signature>(Function, Args...);
// example:
std::bind<bool(*)(unsigned)>(shoot, 3);

方法二,把函数签名作为类型参数传给 static_cast,再将转型后的函数对象(Function Object)传给 std::bind 函数,

// std::bind(static_cast<Signature>(Function), Args...); 
// example:
std::bind(static_cast<bool(Archer::*)(unsigned)>(&Archer::shoot), &hoyt, 5);

◆ 附录

完整示例 how_to_bind_an_overloaded_funtion.cpp

标签:std,shoot,Function,函数,bind,绑定,重载
来源: https://www.cnblogs.com/green-cnblogs/p/15572214.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有