【问题标题】:how to create/pass a completion handler callback as function parameter in c++11?如何在 c++11 中创建/传递完成处理程序回调作为函数参数?
【发布时间】:2017-10-07 13:07:00
【问题描述】:

已经有大量的示例/代码展示了如何将函数作为回调传递给 C++11 中的函数参数。然后回调被调用到一个单独的函数中,而不是它的原始调用者函数中。

假设我在 Objective-C

中有以下示例代码
- (void)calculateSizeWithCompletionBlock:(IPVWebImageCalculateSizeBlock)completionBlock {

    dispatch_async(self.ioQueue, ^{
        NSUInteger fileCount = 0;
        NSUInteger totalSize = 0;

        // Doing some time consuming task, that plays with some local(on this function scope) vars

        if (completionBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(fileCount, totalSize);
            });
        }
    });
}

- (void)doSomething {
    NSUInteger var1 = 0;
    NSUInteger var2 = 0;

    [self calculateSizeWithCompletionBlock:^(NSUInteger fileCount, NSUInteger totalSize) {
        // Here, do things with fileCount, totalSize, var1, var2
        NSLog(@"fileCount: %lu, totalSize: %lu, var1: %lu, var2: %lu",(unsigned long)fileCount, (unsigned long)totalSize, (unsigned long)var1, (unsigned long)var2);
    }];
}

直接的问题是如何在 C++11 中重写上述代码? 我的回调将被调用到调用者函数中,以便它使用调用者函数本地变量。我知道 C++11 的 Lambda、std::function、std::bind,但不知道如何实现。

任何帮助将不胜感激。

【问题讨论】:

  • 我写的这篇文章你可能会感兴趣:vittorioromeo.info/index/blog/…
  • 您是否尝试在调用 GCD 时将 obj-c 闭包替换为 c++ lambda,或者更一般地? GCD 有一个 c 风格的回调接口以及一个基于闭包的回调接口。您可以将闭包对象的地址和函数指针传递给其静态函数。这可以包装在回调函数对象中。
  • 我不了解 Objective-C,但在我看来,您想要的可以通过 [&] lambda 捕获来实现。

标签: c++ objective-c c++11 callback asynccallback


【解决方案1】:
thread_pool& get_threadpool();
void run_on_ui_thread( std::function<void()> );

std::future<void> calculateSizeWithCompletionBlock(
  std::function<void(int fileCount, int totalSize)> completion
) {
  get_threadpool.queue(
    [completion]{
      int fileCount = 0;
      int totalSize = 0;

      // Doing some time consuming task, that plays with some local(on this function scope) vars

      if (completion) {
        RunOnUIThread( [fileCount, totalSize, completion]{
          completion(fileCount, totalSize);
        });
      }
    }
  );
}

void doSomething() {
  int var1 = 0;
  int var2 = 0;

  calculateSizeWithCompletionBlock(
    [var1, var2](int fileCount, int totalSize) {
      // Here, do things with fileCount, totalSize, var1, var2
      std::cout <<
        "fileCount: " << fileCount <<
        ", totalSize: " << totalSize <<
        ", var1: " << var1 <<
        ", var2: " << var2 << "\n";
    }
  );
}

这大致相当于您的代码。

我不包括 run_on_ui_threadget_threadpool,因为两者都取决于您的 C++ 程序运行的上下文。

这是我唯一使用的thread_pool的方法:

struct thread_pool {
  std::future<void> queue( std::function<void()> );
};

基本上,它是一个类似函数的东西,并返回一个让您等待该任务完成的对象。

与 Objective-C 不同,C++ 可以在无数不同的环境中运行。操作系统或其运行的任何其他环境所提供的服务都不是固定的。

例如,没有假设所有 C++ 代码都在交互式 UI 消息泵环境中运行。 run_on_ui_thread 隐含假设,并且必须在编写时考虑到特定的 ui-thread-pump 库。

在 C++14 中,使用 move-into-lambda 可以使上述某些代码的效率略微提高。特别是,

RunOnUIThread( [fileCount, totalSize, completion=std::move(completion)]{
  completion(fileCount, totalSize);
});

就像calculateSizeWithCompletionBlock 一样,我们不知道复制completion 的成本有多高。在 C++ 中,您可以按值更多地访问对象,因此有时您必须显式地移动事物。从好的方面来说,与 Objective-C 相比,这减少了您必须执行的分配量。

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多