使用 shared_from_this 生成函子

尼占姆

我想从一个继承自 enable_shared_from_this 的类 A 创建一个函子,这是一个这样的类:

class A: public std::enable_shared_from_this<A> {
    ...
}

我想要一个看起来像这样的成员函数(不正确的代码):

template <typename Args...>
std::function<void(Args ...)> functor_from_this(void (A::*method)(Args...)) {
    return std::bind(method, shared_from_this());
}

上面的代码生成了几个错误,以 开头warning C4180: qualifier applied to function type has no meaning; ignored,这让我怀疑我以错误的方式处理这个问题。我该如何实现这样的目标?

(a) 将 Args... 绑定到函子的额外学分,因此我得到一个签名为 的函数void fn(),以及 (b) 在继承自enable_shared_from_this<T>.

说书人 - Unslander Monica

好吧,对于 C++14,解决方案很容易编写. 只需放弃std::bind并返回一个lambda:

#include <memory>
#include <iostream>
#include <functional>

struct A: std::enable_shared_from_this<A> {

    template <typename... Args>
    std::function<void(Args...)> functor_from_this(void (A::*method)(Args...)) {
        return [=, obj = shared_from_this()](Args... args) {
          ((*obj).*method)(args...);
        };
    }

    void foo(int) { std::cout << "foo" << '\n'; }
    void bar() { std::cout << "bar" << '\n'; }
};

int main()
{
  auto a = std::make_shared<A>();

  auto f = a->functor_from_this(&A::foo);
  auto b = a->functor_from_this(&A::bar);

  f(1);
  b();
}

对于 Jarod42 在评论中指出的 C++11,使用更简单的中间变量:

#include <memory>
#include <iostream>
#include <functional>

struct A: std::enable_shared_from_this<A> {

    template <typename... Args>
    std::function<void(Args...)> functor_from_this(void (A::*method)(Args...)) {
        auto obj = shared_from_this();
        return [=](Args... args) {
          ((*obj).*method)(args...);
        };
    }

    void foo(int) { std::cout << "foo" << '\n'; }
    void bar() { std::cout << "bar" << '\n'; }
};

int main()
{
  auto a = std::make_shared<A>();

  auto f = a->functor_from_this(&A::foo);
  auto b = a->functor_from_this(&A::bar);

  f(1);
  b();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章