gekomad
gekomad

Reputation: 565

C++ Lambda with template

I'd like to call a lambda with const template value, in example below I should write lambdaTemplate correctly

#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;
}

Upvotes: 4

Views: 4132

Answers (1)

The Philomath
The Philomath

Reputation: 992

You can define lambda like this :

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

and call it like

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

Upvotes: 8

Related Questions