使用boost传递函数指针参数

pin*_*ngu 1 c++ boost boost-bind boost-function

使用boost :: function和/或boost :: bind可以简化/改进以下函数指针传递吗?

void PassPtr(int (*pt2Func)(float, std::string, std::string))
{
   int result = (*pt2Func)(12, "a", "b"); // call using function pointer
   cout << result << endl;
}

// execute example code
void Pass_A_Function_Pointer()
{
   PassPtr(&DoIt);
}
Run Code Online (Sandbox Code Playgroud)

And*_*owl 6

您可以使用boost::function<>不同类型的可调用对象作为函数的输入.

以下是使用C++ 11的示例(请参阅此示例后的备注).这是你重写函数的方法:

#include <functional>
#include <string>
#include <iostream>

void PassFxn(std::function<int(float, std::string, std::string)> func)
//           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
   int result = func(12, "a", "b"); // call using function object
   std::cout << result << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这些是用于测试它的几个函数:

int DoIt(float f, std::string s1, std::string s2)
{
    std::cout << f << ", " << s1 << ", " << s2 << std::endl;
    return 0;
}

int DoItWithFourArgs(float f, std::string s1, std::string s2, bool b)
{
    std::cout << f << ", " << s1 << ", " << s2 << ", " << b << std::endl;
    return 0;
}

struct X
{
    int MemberDoIt(float f, std::string s1, std::string s2)
    {
        std::cout << "Member: " << f << ", " << s1 << ", " << s2 << std::endl;
        return 0;
    }

    static int StaticMemberDoIt(float f, std::string s1, std::string s2)
    {
        std::cout << "Static: " << f << ", " << s1 << ", " << s2 << std::endl;
        return 0;
    }
};
Run Code Online (Sandbox Code Playgroud)

这是测试程序:

int main()
{
    PassFxn(DoIt); // Pass a function pointer...

    // But we're not limited to function pointers with std::function<>...

    auto lambda = [] (float, std::string, std::string) -> int
    {
        std::cout << "Hiho!" << std::endl;
        return 42;
    };

    PassFxn(lambda); // Pass a lambda...

    using namespace std::placeholders;
    PassFxn(std::bind(DoItWithFourArgs, _1, _2, _3, true)); // Pass bound fxn

    X x;
    PassFxn(std::bind(&X::MemberDoIt, x, _1, _2, _3)); // Use a member function!

    // Or, if you have a *static* member function...
    PassFxn(&X::StaticMemberDoIt);

    // ...and you can basically pass any callable object!
}
Run Code Online (Sandbox Code Playgroud)

这是一个实例.

备注:

你可以很容易地改变std::function<>boost::function<>std::bind<>boost::bind<>,如果你是C++ 03的工作(其实来自Boost.Function是什么启发了std::function<>后来成为标准C++库的一部分).在这种情况下,您不必包含<functional>标题,而是必须包含boost/function.hppboost/bind.hpp标题(仅当您要使用时才包含标题boost::bind).

对于另一个例子,它应该让你感受到std::function<>/ boost::function<>通过它封装任何类型的可调用对象的能力,也可以在StackOverflow上看到这个Q&A.