将类成员函数绑定到 std::function 不需要检查参数?

发布于 2025-01-20 06:10:44 字数 1123 浏览 0 评论 0原文

为什么GCC 9.4当将类成员函数绑定到std ::函数可证明的函数时不检查参数,但是检查何时绑定全局函数?这是示例代码,createrpcfun具有一个参数,但是测试成员功能打印除此之外没有其他参数,将打印绑定到createrpcfun效果很好,但是全局funtion print2无法解释为什么?

#include <functional>
#include <iostream>
#include <string>
using namespace std;

using CreateRpcFun = std::function<void(const string &)>;

class Test {
public:
  Test() : str_("nihao!") {}

  // bind print to CreateRpcFun passed compile
  void print() { cout << str_ << endl; }

private:
  string str_;
};

class Holder {
public:
  CreateRpcFun CreateRpc;
};

class Other {
public:
  Other(Holder h, string str) : h_(h), str_(str) {}
  void run() { h_.CreateRpc("world!"); }

private:
  Holder h_;
  string str_;
};

void print1(const string &str) { cout << str << endl; }

void print2() { cout << "magic" << endl; }

int main() {
  Test t;
  Holder h;
  h.CreateRpc = std::bind(&Test::print, &t);

  Other o(h, "hhhh");
  o.run();

  h.CreateRpc = &print1;
  h.CreateRpc("test");

  // h.CreateRpc = &print2; // compile error
  // h.CreateRpc("test");
}

why gcc 9.4 not check parameters when bind a class member funtion to a std::function viriable, but check when bind a global function? here is example code, CreateRpcFun has a parameter, but Test member function print doesn't have any other parameters except this, bind print to CreateRpcFun works well, but global funtion print2 cannot, can anybody explain why?

#include <functional>
#include <iostream>
#include <string>
using namespace std;

using CreateRpcFun = std::function<void(const string &)>;

class Test {
public:
  Test() : str_("nihao!") {}

  // bind print to CreateRpcFun passed compile
  void print() { cout << str_ << endl; }

private:
  string str_;
};

class Holder {
public:
  CreateRpcFun CreateRpc;
};

class Other {
public:
  Other(Holder h, string str) : h_(h), str_(str) {}
  void run() { h_.CreateRpc("world!"); }

private:
  Holder h_;
  string str_;
};

void print1(const string &str) { cout << str << endl; }

void print2() { cout << "magic" << endl; }

int main() {
  Test t;
  Holder h;
  h.CreateRpc = std::bind(&Test::print, &t);

  Other o(h, "hhhh");
  o.run();

  h.CreateRpc = &print1;
  h.CreateRpc("test");

  // h.CreateRpc = &print2; // compile error
  // h.CreateRpc("test");
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文