简体   繁体   English

C++ lambda as std::function 在模板 ZC1C425268E68385D1AB5074C14

[英]C++ lambda as std::function in template function

Let's say we have this simplified version of my code:假设我们有我的代码的这个简化版本:

template<typename R>
R Context::executeTransient(std::function<R(VkCommandBuffer)> const &commands) {
    ...
    R result = commands(commandBuffer);
    ...
    return result;
}

I tried to pass a lambda function as a parameter to the function Context::executeTransient() but it works only if I explicitly assign the lambda to a specific std::function type. I tried to pass a lambda function as a parameter to the function Context::executeTransient() but it works only if I explicitly assign the lambda to a specific std::function type. This works:这有效:

std::function<int(VkCommandBuffer)> f = [](VkCommandBuffer commandBuffer) {
    printf("Test execution");
    return 1;
};
context.executeTransient(f);

The example above works but I'd like to achieve the example below because of aesthetic reasons and don't know if this is even possible:上面的例子有效,但由于美学原因,我想实现下面的例子,不知道这是否可能:

context.executeTransient([](VkCommandBuffer commandBuffer) {
    printf("Test execution");
    return 1;
});

My only requirement is that Context::executeTransient() should accept lambdas and functions with a templated return type and input argument with some specific type eg VkCommandBuffer .我唯一的要求是Context::executeTransient()应该接受具有模板化返回类型的 lambda 和函数以及具有某些特定类型的输入参数,例如VkCommandBuffer

What about simply as follows?简单如下呢?

template <typename F>
auto Context::executeTransient (F const & commands) {
    ...
    auto result = commands(commandBuffer);
    ...
    return result;
}

This way your method accept both standard functions and lambdas (without converting them to standard functions, that is preferable, from the performance point of view (as far as I know)) and the return type is deduced from the use ( auto ).这样,您的方法同时接受标准函数和 lambdas(不将它们转换为标准函数,从性能的角度来看(据我所知)这是更可取的),并且返回类型是从使用( auto )推导出来的。

In you need to know the R type inside the method, you can apply decltype() to result在您需要知道方法内的R类型时,您可以应用decltype()result

     auto result = commands(commandBuffer);

     using R = decltype(result);

If you need to know the R type as template parameter of the method, its a little more complex because involve std::declval() and, unfortunately, add redundancy如果您需要知道R类型作为方法的模板参数,它有点复杂,因为涉及std::declval()并且不幸的是,添加了冗余

template <typename F,
          typename R = decltype(std::declval<F const &>()(commandBuffer))>
R Context::executeTransient (F const & commands) {
    ...
    R result = commands(commandBuffer);
    ...
    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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