繁体   English   中英

将 lambda 作为参数传递给具有任意数量参数的 std::function 参数的函数

[英]Passing lambda as an argument to a function with std::function parameter with an arbitrary number of parameters

考虑下一个代码示例:

template <typename... TArgs>
void foo(std::function<void(TArgs...)> f) {
}

template <typename... TArgs>
class Class {
public:
    static void foo(std::function<void(TArgs...)> f) {
    }
};

为什么我可以这样做:

int main() {
// Helper class call
    Class<int, int>::foo(
        [](int a, int b) {}
    );
}

但是我在这样做时遇到编译错误:

int main() {
// Function call
    foo<int, int>(
        [](int a, int b) {}
    );
}
<source>:16:5: error: no matching function for call to 'foo'
    foo<int, int>(
    ^~~~~~~~~~~~~

<source>:4:6: note: candidate template ignored: could not match
    'std::function<void (int, int, TArgs...)>' against 
    '(lambda at <source>:17:9)'

void foo(std::function<void(TArgs...)> f) {
     ^

我只是想有一种方便的方式来使用诸如foo之类的功能。

我试过这个:


std::function<void(int, int)> f = [](int a, int b) {
    };

    foo<int, int>(f); // ok

它奏效了。 这没关系。 但我想知道是否有任何方法可以在函数调用中直接使用 lambda,而无需创建本地函数对象。

因为这个: Why is template parameter pack used in a function argument type as its template argument list not can be explicited specified

当您调用foo<int, int>([](int a, int b) {}); , 包TArgs仍然被推导以防需要扩展。 std::function<void(TArgs...)>无法使用 lambda 参数为TArgs...推导任何内容,因此它被推导为一个空包,这与给定的int, int冲突。

对于Class<int, int>::foo ,没有模板参数推导,因为模板参数已经给出。

对此的解决方法是将其置于非推导上下文中:

template <typename... TArgs>
void foo(std::type_identity_t<std::function<void(TArgs...)>> f) {
}

或者根本不使用std::function

template <typename F>
void foo(F&& f) {
}

暂无
暂无

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

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