如何用成员函数初始化`std :: function`? [英] How to initialize `std::function` with a member-function?

查看:728
本文介绍了如何用成员函数初始化`std :: function`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 std :: function ,这是我的代码:

I am trying to learn std::function and here's my code:

#include <iostream>
#include <functional>

struct Foo {
    void print_add(int i){ 
      std::cout << i << '\n'; 
    }
};

typedef std::function<void(int)> fp;

void test(fp my_func)
{
  my_func(5);
}

int main(){
    Foo foo;
    test(foo.print_add);
    return 0;
}

编译器错误:

 error: cannot convert 'Foo::print_add' from type 'void (Foo::)(int)' to type 'fp {aka std::function<void(int)>}'
     test(foo.print_add);

如何进行这项工作,即如何将成员函数作为参数传递? p>

How can I make this work, i.e how can I pass a member function as a parameter?

推荐答案

print_add foo ,这意味着必须在 Foo 的实例上调用它;因此,它有一个隐式的第一个参数,即 this 指针。

print_add is a non-static member function of foo, which means it must be invoked on an instance of Foo; hence it has an implicit first argument, the this pointer.

使用可捕获<$ c $的lambda c> foo 实例并对其调用 print_add

Use a lambda that captures the foo instance and invokes print_add on it.

Foo foo;
test([&foo](int i){ foo.print_add(i); });

另一种选择是使用 std :: bind 绑定 foo 实例:

Another option is to use std::bind to bind the foo instance:

test(std::bind(&Foo::print_add, &foo, std::placeholders::_1));

实时演示

这篇关于如何用成员函数初始化`std :: function`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆