简体   繁体   English

在C ++ 11中创建并返回包含lambda成员变量的类

[英]Creating and returning a class containing lambda member variable in C++11

I have the following class which contains a lambda member variable: 我有以下类,其中包含一个lambda成员变量:

template <typename Callable>
class task {
  private:
    Callable lambda;

  public:
    task(Callable l) : lambda(l) {}

    void execute() {
        lambda();
    }
};

Now I want to create a function which accepts a object of any class and a member function pointer of that class, then creates lambda, creates a task from that lambda and finally returns the task. 现在我想创建一个函数,它接受任何类的对象和该类的成员函数指针,然后创建lambda,从该lambda创建一个任务,最后返回任务。 But I can't figure out the return type of the function: 但我无法弄清楚函数的返回类型:

template <typename C, typename F, typename ...Args>
/* return type ?*/ create_task(C& obj, F func, Args... args) {
    auto l = [&obj, func, args...] {
        (obj.*func)(args...);
    };

    task<decltype(l)> t {l};

    return t;
}

How can this be done in C++11 ? 如何在C++11 I'm also open for other suggestions, BUT they'll have to do without dynamic memory allocation. 我也愿意接受其他建议,但他们不得不做动态内存分配。

Due to limitations on how type deduction works in C++11, you'd have to roll your own callable instead of using a lambda 由于类型推导在C ++ 11中如何工作的限制,你必须滚动你自己的可调用而不是使用lambda

template<typename C, typename F, typename... Args>
struct task
{
    C* c;
    F C::* f;
    std::tuple<typename std::decay<Args>::type...> args;

    task(C* c, F C::* f, Args&&... args) 
      : c{c}, f{f}, args{std::forward<Args>(args)...} {}

    void execute()
    {
        auto l = [&](Args&... args) {
            (c->*f)(args...);
        };
        std::apply(l, args);
    }
};

template<typename C, typename F, typename... Args>
auto create_task(C& c, F C::* f, Args&&... args) -> task<C, F, Args...>
{
    return {&c, f, std::forward<Args>(args)...};
}

Where std::apply can be implemented in C++11 like this . 其中std::apply可以像这样在C ++ 11中实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM