【问题标题】:C++ template for Runnable functionRunnable 函数的 C++ 模板
【发布时间】:2021-05-10 19:45:22
【问题描述】:

我正在为我的应用程序使用 C++ 编写线程管理库,作为其中的一部分,我正在尝试编写一个模板类,该类需要在 run 函数中执行 FunctionPointer。我是一名 Java 开发人员,并尝试如下进行可视化:

class MyRunnable : public Runnable {

    public:
        MyRunnable(fp)
        {
            mFp = fp;
        }

    private:

    FunctionPointer mFp;

    // Will be called by the thread pool using a thread
    void run() 
    {
         mFp();
    }

}

class ThreadManager {

    public:
        void execute(MyRunnable runnable) {
            executeOnAThreadPool(runnable);
        }

}

由于我不熟悉 C++ 语法,我发现很难将构造函数定义为将FunctionPointer 作为FunctionPointer 的可变数量参数的参数。比如:

MyRunnable(Fp fp, Args... args)

谁能帮我定义上面MyRunnable 类的构造函数。 谢谢。

【问题讨论】:

  • 我建议你先尝试现有的 C++ 库,同时学习 lambdas、Invokables、std::thread's 等。
  • 调用mFp();时可以传递参数。您还需要将这些作为run() 的参数提供,或者在构造函数中提供,以存储为类成员变量以供以后使用。
  • 你可以省去你的Runnable接口。 std::function 用途广泛,可以很好地满足您的需求。
  • @πάνταῥεῖ 是的,我正在寻找一个模板来将参数传递给构造函数并保存为成员变量。我如何实现它?
  • @StoryTeller-UnslanderMonica 请告诉我如何使用 std::function 来解决我的问题。

标签: c++ c++11 lambda poco poco-libraries


【解决方案1】:

不确定...但在我看来,您看起来像

class MyRunnable
 {
   private:
      std::function<void()> mF;

   public:       
      template <typename F, typename ... Args>
      MyRunnable (F && f, Args && ... args)
       : mF{ [&f, &args...](){ std::forward<F>(f)(std::forward<Args>(args)...); } }
       { }

      void run ()
       { mF(); }
 };

以下是完整的编译示例

#include <iostream>
#include <functional>

class MyRunnable
 {
   private:
      std::function<void()> mF;

   public:       
      template <typename F, typename ... Args>
      MyRunnable (F && f, Args && ... args)
       : mF{ [&f, &args...](){ std::forward<F>(f)(std::forward<Args>(args)...); } }
       { }

      void run ()
       { mF(); }
 };

void foo (int a, long b, std::string const & c)
 { std::cout << "executing foo() with " << a << ", " << b << ", " << c << '\n'; }

int main ()
 {
   MyRunnable  mr{foo, 1, 2l, "three"};

   std::cout << "before run" << '\n';

   mr.run();

 }

打印出来的

before run
executing foo() with 1, 2, three

【讨论】:

  • 非常感谢。 C++ 简直太棒了。如果我有类 Foo 的成员函数,比如 Foo::a,我如何将它传递给 MyRunnable ?使用 MyRunnable mr{&Foo::A};抛出编译错误“无法创建指向成员函数的非常量指针”
  • @Androider 成员函数(直接调用时)采用隐式的第一个参数:指向对象的指针。看看这里:stackoverflow.com/a/17131787/4885321 编辑:如果您想将对象作为参数传递给它,请查看mem_fn
  • @Androider - “我如何将它传递给 MyRunnable ?” - 你还想传递Foo 类型的对象吗?
  • @max66 我要求类似: class Foo { void print(int x) { // print something } void doSomething() { MyRunnable run {&Foo::print, x};酒吧::threadPoolRun(运行); } }
  • @Androider - 如果你想执行Foo::print(),你需要(如果print() 不是staticFoo 对象。谁提供Foo 对象?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
相关资源
最近更新 更多