c++ - 将N-arg函数包装到另一个函数中

标签 c++ variadic-templates std-function

我有一个在 worker 线程中执行另一个功能的函数:

void run_in_worker_thread( std::function< void( ) > proc )

现在,我想实现函数 schedule(),该函数将 proc()函数作为参数,并返回通过 run_in_worker_thread()在工作线程中执行 proc()的函数。

这是我的实现:
#include <iostream>
#include <functional>

using namespace std;

class Test
{
  public:
    void run_in_worker_thread( std::function< void( ) > proc )
    {
            std::cout << "execute in worker thread\n";
            proc();
    }

    template < class... TArgs >
    std::function< void( TArgs... ) >
    schedule( std::function< void( TArgs... ) > proc )
    {
        std::function< void( TArgs... ) > f
                = [this, proc]( TArgs... args ) { run_in_worker_thread( [=]( ) { proc( args... ); } ); };
        return f;
    }  
};

int main()
{
    Test test;
    std::function<void(int, int)> my_funciton = 
         [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
    auto f2 = test.schedule( my_funciton );
    f2(1, 2);
    return 0;
}

问题是我的 schedule()需要std::function作为参数。例如,以下调用导致编译错误:
    auto my_funciton = [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
    auto f2 = test.schedule( my_funciton );

最佳答案

问题是std::function是可调用对象周围的多态包装。 Lambda不是std::function。就像字符串文字不是std::string一样。在第一个示例中,您将执行以下操作:

std::function<void(int, int)> my_funciton = 
     [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};

您正在从lambda构造std::functionschedule函数能够推断出该函数的签名而不会出现问题。

在第二个示例中,您将执行以下操作:
auto my_funciton = [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};

然后,您将收到一个错误,因为std::function<void (Args...)>无法与lambda匹配。解决方案是允许schedule接受任何可调用的对象,而不仅仅是std::function
template <typename Func>
auto schedule(Func proc) {
  return [this, proc](auto... args) {
    run_in_worker_thread([=]() {
      proc(args...);
    });
  };
}

关于c++ - 将N-arg函数包装到另一个函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60243634/

相关文章:

c++ - 如何计算 std::vector<int>::iterator 和 std::vector<int>::reverse_iterator 之间的距离?

c++ - 如何优化 SDL 2 中许多纹理的渲染?

c++ - 如果模板模板参数是 vector ,则需要不同的行为

c++ - 如何使用 C++14 和 C++1z 中的功能缩短此可变参数模板代码?

c++ - 是否可以从函数模板返回可变参数 lambda?

c++ - 在模板参数中扩展类型 N 次

c++ - Petsc 添加矩阵值

c++ - 使用迭代器的通用构造函数

c++ - std::function不起作用,但是普通的旧函数指针起作用-为什么?

c++ - 成员函数可以在自由函数可以使用 std::function 的任何地方使用吗?