带模板的 C++ Lambda

gek*_*mad 2 c++ lambda templates c++20

我想用 const 模板值调用 lambda,在下面的示例中,我应该lambdaTemplate正确编写

#include <iostream>

using namespace std;

template<int bar, int baz>
int foo(const int depth) {
    return bar + baz + depth;
}

int main() {
    ////// call function
    cout << foo<1, 2>(10) << endl; // 13

    ///// call lambda without template value
    const auto lambda1 = [&](const int v) {
        return foo<1, 2>(v);
    };
    cout << lambda1(10) << endl; // 13

    ///// call lambda with template value
    const auto lambdaTemplate = [&]<A,B ??? >(const int v) { // <-- ERROR doesn't compile
        return foo<A,B>(v);
    };

    cout << lambdaTemplate<1,2>(10) << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

The*_*ath 6

您可以像这样定义 lambda:

auto lambdaTemplate = [&]<int T1, int T2>(const int v) {
    return foo<T1, T2>(v);
};
Run Code Online (Sandbox Code Playgroud)

并称之为

std::cout << lambdaTemplate.operator()<1,2>(10);
Run Code Online (Sandbox Code Playgroud)