带模板的C++Lambda

我想用 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;
}

回答

您可以像这样定义 lambda:

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

并称之为

std::cout << lambdaTemplate.operator()<1,2>(10);


以上是带模板的C++Lambda的全部内容。
THE END
分享
二维码
.

)">
< <上一篇
下一篇>>