简体   繁体   English

如何使用boost :: bind将静态成员函数绑定到boost :: function

[英]How to bind a static member function to a boost::function using boost::bind

I want to bind a static member function to a boost::function using boost::bind. 我想使用boost :: bind将静态成员函数绑定到boost :: function。 The following is an example of what I want to do (not working). 以下是我想做的事(不起作用)的一个例子。

class Foo {
public:
    static void DoStuff(int param)
    {
        // To do when calling back
    }
};


class Question {
public:
    void Setup()
    {
        AssignCallback(boost::bind(&Foo::DoStuff, _1));  // How to bind the static funciton here
    }

    void AssignCallback(boost::function<void(int param)> doStuffHandler)
    {
        ...
        ...
    }
};

I have previously used boost::bind with member functions using this syntax: 我以前使用过boost ::: bind和成员函数,使用的语法是

boost::bind(&Foo::NonStaticMember, this, _1, _2, _3, _4)

But this is obviously not correct for a static member. 但这对于静态成员显然是不正确的。

Can you please explain to me how to correctly bind a static member function of a class using boost::bind? 您能告诉我如何使用boost :: bind正确绑定类的静态成员函数吗?

It will be done as you do for normal functions binding. 它将像常规函数绑定一样完成。 For static function you just need to use its class name for to recognize the function by the compiler and skip the this argument since static finctions are bound to class not to the object. 对于静态函数,您只需要使用其类名即可由编译器识别该函数,并跳过此参数,因为静态函数是绑定到类的,而不是绑定到该对象的。 Below is a simple example: 下面是一个简单的示例:

#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
void test(boost::function<bool(int, int)> func)
{
    std::cout<<"in test().\n";
    bool ret = func(10, 20);
    std::cout<<"Ret:"<<ret<<"\n";
}
class Test
{
    public:
    static bool test2(int a, int b)
    {
            std::cout<<"in test2().\n";
            return a>b;
    }
};

int main()
{
    test(boost::bind(&Test::test2, _1, _2));
    return 0;
}

O/P:
in test().
in test2().
Ret:0

You should not use this as static functions dont have this pointer. 您不应该使用此功能,因为静态函数没有此指针。

int main()
{
    test(boost::bind(&Test::test2, this, _1, _2));-----> Illegal
    return 0;
}
Below error will occur:
techie@gateway1:myExperiments$ g++ boost_bind.cpp
boost_bind.cpp: In function âint main()â:
boost_bind.cpp:26: error: invalid use of âthisâ in non-member function

Hope this will help. 希望这会有所帮助。 :-) :-)

Your code is correct. 您的代码是正确的。 Maybe you experience some compiler issue? 也许您遇到了一些编译器问题? Can you cite the compilation output? 您可以引用编译输出吗?

You can also try using std::function and std::bind instead. 您也可以尝试使用std :: function和std :: bind代替。 Only replace boost headers with "functional" header and write 仅将boost头替换为“ functional”头并写入

std::placeholders::_1

instead of 代替

_1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM