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

How to bind a static member function to a boost::function using boost::bind

本文关键字:boost 绑定 function 函数 何使用 bind 静态成员      更新时间:2023-10-16
我想使用 boost::

bind 将静态成员函数绑定到 boost::function。以下是我想做什么(不工作)的示例。

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)
    {
        ...
        ...
    }
};

我以前使用以下语法将 boost::bind 与成员函数一起使用:

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

但这显然对于静态成员是不正确的。

你能向我解释如何使用 boost::bind 正确绑定类的静态成员函数吗?

它将像普通函数绑定一样完成。对于静态函数,您只需要使用其类名来识别编译器的函数并跳过 this 参数,因为静态 finctions 绑定到类而不是对象。下面是一个简单的例子:

#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

不应使用它,因为静态函数没有此指针。

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

希望这会有所帮助。

你的代码是正确的。也许您遇到一些编译器问题?你能引用编译输出吗?

您也可以尝试使用 std::

function 和 std::bind 代替。仅将提升标头替换为"功能"标头并写入

std::placeholders::_1

而不是

_1