简体   繁体   中英

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

I have the following class which contains a lambda member variable:

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. 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 ? 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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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