boost :: bind with null function pointer

Mat*_*ner 7 c++ boost bind function-pointers boost-bind

如果嵌入在boost::bind返回对象中的函数指针是NULL/ nullptr/ 0,我需要采取除调用之外的操作.如何确定对象是否包含空函数指针?

附加物

  1. 我不相信我可以使用和比较boost::functions,因为boost::bind返回对象与模板函数中的不同调用签名一起使用.
  2. 简化示例:
template <typename BRO>
Retval do_stuff(BRO func, enum Fallback fallback)
{
    if (func == NULL)
    {
        return do_fallback(fallback);
    }
    else
    {
        return use_retval(func());
    }
}

do_stuff(boost::bind(FuncPtrThatMightBeNull, var1, var2), fallback);
Run Code Online (Sandbox Code Playgroud)

由于被调用者中的函数的arity没有改变,我可以将绑定返回对象"转换"为a boost::function和call.empty()

Retval do_stuff(boost::function<Retval()> func, enum Fallback fallback)
{
    if (func.empty())
        return do_fallback(fallback);
    else
        return use_retval(func());
}
Run Code Online (Sandbox Code Playgroud)

Geo*_*che 5

您可以绑定到虚拟函数:

void dummy() { /* has differing behaviour */ }
// ...
boost::bind(&dummy)();
Run Code Online (Sandbox Code Playgroud)

...或者,假设您Boost.Bind一起使用Boost.Function,返回默认构造的函数对象并empty()在调用它之前检查:

typedef boost::function<void (void)> F;
F create() { return F(); }

void use() {
    F f = create();
    if(f.empty()) {
        /* ... */
    }
}
Run Code Online (Sandbox Code Playgroud)

关于更新:
我仍然没有看到绑定到不同函数的问题是什么,如下所示:

template <typename BRO>
Retval do_stuff(BRO func)
{
    return func();
}

if(funcPtr) {
    do_stuff(boost::bind(&use_retval, boost::bind(funcPtr, a, b)));
} else {
    do_stuff(boost::bind(&do_fallback, fallback));
}
Run Code Online (Sandbox Code Playgroud)

如果您想要将该处理移出调用代码,您可以模拟可变参数模板函数来支持变量arities:

template<class R, class T1> 
boost::function<R (T1)> 
bind_wrap(R (*fnPtr)(), T1& t1, Fallback fallback) {
    if(fnPtr) return boost::bind(&use_retval,  boost::bind(funcPtr, t1));
    else      return boost::bind(&do_fallback, fallback);
}

template<class R, class T1, class T2> 
boost::function<R (T1, T2)> 
bind_wrap(R (*fnPtr)(T1, T2), T1& t1, T2& t2, Fallback fallback) {
    if(fnPtr) return boost::bind(&use_retval,  boost::bind(funcPtr, t1, t2));
    else      return boost::bind(&do_fallback, fallback);
}

// ... etc. for all needed arities

do_stuff(bind_wrap(funcPtr, var1, var2, fallback));
Run Code Online (Sandbox Code Playgroud)

...或者您使用上述方法生成boost::function<>对象或您自己的包装并检查functor.empty()或类似do_stuff().