std函数-C++弱函子解

std function - C++ weak functor solution

本文关键字:函数 -C++ std      更新时间:2023-10-16

这是void()函数特有的,但对我来说没问题…

struct Foo
{
   void Bar(int x)
   {
      std::cout << x << std::endl;
   }
};
struct VoidBind
{
    typedef void result_type;
    template<typename T> void operator()(const std::weak_ptr<T>& obj, std::function<void()>& func)
    {
        std::shared_ptr<T> shared_obj = obj.lock();
        if (shared_obj)
        {
            func();
        }
    }
    template<typename T> static std::function<void()> bind(const std::shared_ptr<T>& obj, const std::function<void()>& func)
    {
        return std::bind(VoidBind(), std::weak_ptr<T>(obj), func);
    }
};
#define BIND(F, O, A...)  VoidBind::bind(O, std::function<void()>(std::bind(F, O.get(), ##A)))

此代码随后被调用为…

auto obj = std::make_shared<Foo>();
auto func = BIND(&Foo::Bar, obj, 99);  // match std::bind style
func();
obj.reset();  // destroy object
func();       // will not do anything

我的问题是,是否有某种方法可以避免BIND宏?

这里可以使用可变模板:

template<class F, class O, class... Args>
auto bind(F f, O&& o, Args&&... args)
    -> decltype(VoidBind::bind(o, std::function<void()>(std::bind(f, O.get(), args...))))
{
    return VoidBind::bind(O, std::function<void()>(std::bind(F, O.get(), args...)));
}

使用C++14自动返回类型扣除,甚至不需要指定返回值,效果会更好:

template<class F, class O, class... Args>
auto bind(F f, O&& o, Args&&... args)
{
    return VoidBind::bind(o, std::function<void()>(std::bind(f, O.get(), args...)));
}

您是否考虑过使用lambda表达式而不是函子对象——功能相同,但更紧凑,并且绑定是lambda声明的一部分。