4

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; } 
4
  • Are you using a compiler that does support template parameters for lambdas? This is a pretty new feature (C++20). In that case the template parameters should be similar to those of foo. Commented Jan 10, 2021 at 11:56
  • Yes I use C++20 Commented Jan 10, 2021 at 12:05
  • Even with C++20, the template argument must be deducible (or the nice syntax is not available). Either way, if what you want is a capturing lambdaTemplate<1,2>(10), that's a non-starter. Commented Jan 10, 2021 at 12:18
  • 1
    You can get lambdaTemplate(constant<1>, constant<2>)(10) to work, however. Commented Jan 10, 2021 at 15:12

1 Answer 1

9

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); 
Sign up to request clarification or add additional context in comments.

3 Comments

Note that lambdaTemplate is not a dependent name, and you shall thus not use the template keyword when accessing the conversion function template. At best this is redundant, but at worst ill-formed (but accepted by some compilers nonetheless), as covered in the following Q&A.
@dfrib: The parser guides are nowadays allowed in non-dependent contexts (which I fear merely encourages the popular confusion about their purpose), so long as it is in fact a template-id that follows.
@DavisHerring I see, thanks. I see I even pointed this out in my self-answer to the linked Q&A, but had since forgot it; it is indeed a bit confusing (and somewhat counter-intuitive) that this is allowed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.