2

関数へのジェネリックポインタを宣言できないようです。

次の2つの関数を呼び出す必要があります。

void myfunc1(std::string str)
{
    std::cout << str << std::endl;
}
struct X
{
        void f(std::string str){ std::cout<< str << std::endl;}
};

そしてこれらの2つの関数呼び出し元:

typedef void (*userhandler_t) (std::string);
struct example
{   
    userhandler_t userhandler_;

    example(userhandler_t userhandler): userhandler_(userhandler){}

    void call(std::string str)
    {   
        userhandler_(str);
    }
};
template<typename func_t>
void justfunc(func_t func)
{
    func("hello, works!");
}

これらをboost::bindで使用してメンバー関数を呼び出そうとすると、コンパイルエラーが発生します。

これは機能します:

example e1(&myfunc1);
e1.call("hello, world!");
justfunc(&myfunc1);

これはしません:

X x;
example e2(boost::bind(&X::f, &x, _1));
e2.call("hello, world2!");
justfunc(boost::bind(&X::f, &x, _1));

これはどのように行われることになっていますか?

4

1 に答える 1

7

boost::bind実際の関数ポインタではなく、関数のように動作するオブジェクトを作成します。Boost.Functionライブラリを使用して、呼び出しの結果を保持しますboost::bind

struct example
{
    boost::function<void(std::string)> userhandler_;
    ...
};
于 2010-05-20T12:24:13.043 に答える