c++ - 如何将 std::bind 与标准库一起使用并保存返回类型?

标签 c++ c++11 stl bind

我正在开发一个类,它通过将函数绑定(bind)在队列中来调度函数,如下所示:

std::queue <void()> q;

template<typename R,typename... ArgsT>
        void
        schedule(R& fn, ArgsT&... args)
        {
            q.push(std::bind(fn, std::forward<ArgsT>(args)...) );
        };

template<typename R,typename... ArgsT>
        void
        schedule(R&& fn, ArgsT&&... args)
        {
            q.push(std::bind(fn, std::forward<ArgsT>(args)...) );
        };

如您所见,我在 queue void() 中创建了类型,以使其保存任何类型的函数对象,但现在当我执行它。我应该怎么做才能解决这个问题?

注意:我不想使用像boost这样的外部库,并且我不知道用户会传递什么样的函数。

最佳答案

Note: I don't want to use an external library like boost and I don't know what's the kind of function the user will pass it.

在这种情况下,我通常做的是在队列中使用基类(来自命令模式),然后有两个实现,一个包装绑定(bind),另一个(也包装绑定(bind))公开一个函数,该函数允许获取返回值。

这是返回特化的示例(最后):

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


struct ACmd
{
  virtual void exec() = 0;
  virtual ~ACmd(){}
};

template <class F>
struct Cmd;

template <class R, class ... Args>
struct Cmd<R(Args...)> : ACmd
{
  R result_;
  std::function<R()> func_;

  template <class F>
  Cmd(F&& func, Args&&... args): result_(), func_()
  {
    auto f = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
    func_ = [f](){
      return f();
    };
  }

  virtual void exec(){
    result_ = func_();
  }

  const R& getResult() const {return result_;}
};

// Make function for convenience, could return by value or ptr - 
//  - your choice
template <class R, class F, class ...Args>
Cmd<R(Args...)>* cmd(F&& func, Args&&... args)
{
  return new Cmd<R(Args...)>(func, std::forward<Args>(args)...);
}

//... And overload for void...

int foo(int arg) {
  return arg;   
}

int main() {

  auto x = cmd<int>(foo, 10);
  x->exec();
  std::cout << x->getResult() << std::endl;
  return 0;
}

关于c++ - 如何将 std::bind 与标准库一起使用并保存返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45947896/

相关文章:

c++ - 如果数组中的所有值都为真,则退出函数

c++ - 遍历 C++ 映射时的奇怪行为

c++ - 在 opengl 子窗口上渲染一个 qt 覆盖窗口

c++ - 对原子变量的非原子操作

c++ - 获取 std::stack 后面的容器

c++ - 如何使用 vector c++迭代文件中单词的位置

c++ - 如何在映射中使用存储指向成员函数的指针的 Binder2nd 对象?

c++ - wxWidgets 运行时错误(版本不匹配)

c++ - 交换两个完整的 vector/队列/堆栈时间成本?

c++ - 从 vector<> 中删除重复项的最快方法