簡體   English   中英

如何使用boost :: bind將靜態成員函數綁定到boost :: function

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

我想使用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正確綁定類的靜態成員函數嗎?

它將像常規函數綁定一樣完成。 對於靜態函數,您只需要使用其類名即可由編譯器識別該函數,並跳過此參數,因為靜態函數是綁定到類的,而不是綁定到該對象的。 下面是一個簡單的示例:

#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代替。 僅將boost頭替換為“ functional”頭並寫入

std::placeholders::_1

代替

_1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM