gpt4 book ai didi

c++ - 使用 shared_from_this 生成仿函数

转载 作者:搜寻专家 更新时间:2023-10-31 00:54:57 24 4
gpt4 key购买 nike

我想从继承自 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... 绑定(bind)到仿函数的额外学分,因此我得到一个签名为 void fn() 的函数, (b) 在继承自 enable_shared_from_this<T> 的通用类中执行所有这些操作.

最佳答案

嗯,对于 C++14,解决方案是 easy enough to write .只需放弃 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();
}

关于c++ - 使用 shared_from_this 生成仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43632324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com