代码之家  ›  专栏  ›  技术社区  ›  João Portela

指向(成员?)函数的c++泛型指针

  •  2
  • João Portela  · 技术社区  · 14 年前

    我似乎不能声明指向函数的泛型指针。

    具有以下两个要调用的函数:

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

    这两个函数调用者:

    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));
    

    这应该怎么做?

    1 回复  |  直到 14 年前
        1
  •  7
  •   Marcelo Cantos    14 年前

    boost::bind 创建行为类似于函数的对象,而不是实际的函数指针。使用Boost.Function库保存调用的结果 boost::绑定 :

    struct example
    {
        boost::function<void(std::string)> userhandler_;
        ...
    };