C++ boost::指向参数的函数指针?

C++ boost::指向参数的函数指针?,c++,boost,C++,Boost,函数如何获取函数指针并从中获取参数?我想要包装一个函数指针,以便在调用之前对其进行验证。如果能够像boost::function使用()操作符一样调用它,而不必访问函数指针成员,那就太好了 Wrapper func; func(5); //Yes :D func.Ptr(5) //Easy to do, but not as nice looking 包装函数; func(5)//是的:D func.Ptr(5)//很容易做,但没有那么好看 您需要重载操作符()。要确定函数的返回

函数如何获取函数指针并从中获取参数?我想要包装一个函数指针,以便在调用之前对其进行验证。如果能够像boost::function使用()操作符一样调用它,而不必访问函数指针成员,那就太好了

Wrapper func; func(5); //Yes :D func.Ptr(5) //Easy to do, but not as nice looking 包装函数; func(5)//是的:D func.Ptr(5)//很容易做,但没有那么好看
您需要重载
操作符()
。要确定函数的返回类型、arity和参数类型,可以使用类似Boost.TypeTraits的内容:

#include <boost/type_traits.hpp>

template <typename Function>
struct Wrapper
{
    typedef typename boost::function_traits<Function>::arg1_type Arg1T;
    typedef typename boost::function_traits<Function>::result_type ReturnT;

    Wrapper(Function func) : func_(func) { }

    ReturnT operator()(Arg1T arg) { return func_(arg); }

    Function* func_;
};

bool Test(int x) { return x < 42; }

int main()
{
    Wrapper<bool(int)> CallsTest(&Test);
    CallsTest(42);
}
#包括
模板
结构包装器
{
typedef typename boost::function_traits::arg1_type Arg1T;
typedef typename boost::function_traits::result_type ReturnT;
包装器(函数func):func_(func){}
ReturnT运算符()(Arg1T arg){return func(arg);}
函数*func;
};
布尔测试(intx){返回x<42;}
int main()
{
包装调用测试(和测试);
CallsTest(42);
}
像这样的东西

class Functor
{
public:

    /// type of pointer to function taking string and int and returning int
    typedef int ( *func_ptr_t )( const std::string&, int );

    explicit Functor( func_ptr_t f ) : fptr_( f ) {}

    int operator()( const std::string& s, int i ) const { return fptr_( s, i ); }

private:

    func_ptr_t fptr_; //< function pointer
};
类函子
{
公众:
///指向接受字符串和int并返回int的函数的指针类型
typedef int(*func_ptr_t)(常量std::string&,int);
显式函子(func_ptr_t f):fptr_(f){
int运算符()
私人:
函数指针
};

但是为什么不直接使用
boost::function
?它允许的不仅仅是一个函数指针。

我理解这一点,但是如何从函数指针到参数,这样就可以重载它呢?我想我可以。我需要一种从它继承并重载()操作符的方法。我不想像您在示例中那样内联参数。嗯,我看不出有什么意义。为什么在函数指针周围需要一个包装器并从中继承<另一方面,code>boost::function,将允许您指向任何确认可调用对象的签名,并允许按值存储它,这对于STL容器非常方便。然后我将签出可调用对象。因为我需要在调用函数之前验证它是否有效。我试图使从动态加载的dll调用成员函数变得容易。因此,在调用它之前,如果它为null,它将尝试使用GetProcAddress获取它,如果它仍然为null,它将返回。我认为这对于延迟库加载来说太麻烦/太一般了。此外,如果库未加载或未找到所需函数,我会引发一个异常,而不是返回(什么?),至少上层知道有问题。