【问题标题】:using bind with member function [duplicate]使用与成员函数绑定[重复]
【发布时间】:2013-09-11 11:46:18
【问题描述】:

为什么bind 两个版本都可以毫无问题地编译和工作,即使我在每次调用中使用不同的参数类型?

  1. 版本 1 -> 参数 foo 与
  2. 版本 2 -> foo 的参数地址

我预计版本 1 会产生编译错误...


#include <iostream>
#include <functional>

using namespace std;

class Test   
{   
public:
   bool doSomething(){ std::cout << "xxx"; return true;};   
};

int main() {

Test foo;

// Version 1 using foo
std::function<bool(void)> testFct = std::bind(&Test::doSomething, foo);

// Version 2 using &foo
std::function<bool(void)> testFct2 = std::bind(&Test::doSomething, &foo);

testFct();
testFct2();

return 0;
}

【问题讨论】:

  • 因为您可以在对象和指向对象的指针上调用成员函数?
  • 重复回答我的问题

标签: c++ c++11


【解决方案1】:
std::function<bool(void)> testFct = std::bind(&Test::doSomething, foo);

这将绑定到foo副本,并将函数调用为copy.doSomething()。请注意,如果您希望在 foo 本身上调用该函数,这将是错误的。

std::function<bool(void)> testFct2 = std::bind(&Test::doSomething, &foo);

这将绑定到一个指向foo指针,并将函数调用为pointer-&gt;doSomething()。请注意,如果foo 在调用函数之前已经被销毁,这将是错误的。

我预计版本 1 会产生编译错误...

如果您愿意,可以通过将 Test 设为不可复制来禁止此行为。

【讨论】:

    猜你喜欢
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    相关资源
    最近更新 更多