在一个类中使用具有成员函数的通用 std::function 对象 [英] Using generic std::function objects with member functions in one class

查看:27
本文介绍了在一个类中使用具有成员函数的通用 std::function 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个类,我想在一个存储 std::function 对象的 map 中存储一些指向同一类成员函数的函数指针.但是我一开始就失败了,这段代码:

For one class I want to store some function pointers to member functions of the same class in one map storing std::function objects. But I fail right at the beginning with this code:

#include <functional>

class Foo {
    public:
        void doSomething() {}
        void bindFunction() {
            // ERROR
            std::function<void(void)> f = &Foo::doSomething;
        }
};

我收到 错误 C2064:在 xxcallobj 中,term 未评估为采用 0 个参数的函数,并结合了一些奇怪的模板实例化错误.目前我正在使用 Visual Studio 2010/2011 在 Windows 8 上工作,在使用 VS10 的 Win 7 上它也失败了.该错误必须基于我不遵循的一些奇怪的 C++ 规则

I receive error C2064: term does not evaluate to a function taking 0 arguments in xxcallobj combined with some weird template instantiation errors. Currently I am working on Windows 8 with Visual Studio 2010/2011 and on Win 7 with VS10 it fails too. The error must be based on some weird C++ rules i do not follow

推荐答案

必须使用对象调用非静态成员函数.也就是说,它总是隐式地传递this"指针作为它的参数.

A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument.

因为您的 std::function 签名指定您的函数不接受任何参数 (<void(void)>),您必须 绑定第一个(也是唯一的)参数.

Because your std::function signature specifies that your function doesn't take any arguments (<void(void)>), you must bind the first (and the only) argument.

std::function<void(void)> f = std::bind(&Foo::doSomething, this);

如果要绑定带参数的函数,需要指定占位符:

If you want to bind a function with parameters, you need to specify placeholders:

using namespace std::placeholders;
std::function<void(int,int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);

或者,如果您的编译器支持 C++11 lambdas:

Or, if your compiler supports C++11 lambdas:

std::function<void(int,int)> f = [=](int a, int b) {
    this->doSomethingArgs(a, b);
}

(我手头没有支持 C++11 的编译器,所以我无法检查这个.)

(I don't have a C++11 capable compiler at hand right now, so I can't check this one.)

这篇关于在一个类中使用具有成员函数的通用 std::function 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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