1

I'm trying to use a lambda which have two specializations, but it seems I'm doing something wrong. I tried to search here, but I couldn't find nothing, except this:

How to invoke a lambda template?

Which doesn't help too much in my case. Please, could you tell me how should I invoke lambdas with my specializations? I'm working with Visual Studio 2019 16.9.2 (I cannot update yet)

auto testLamb = []<typename T, int max = 2>(T data)
{
    if constexpr (max == 0)
    {
        return data;
    }
    else
    {
        return data + max;
    }
};

int f1 = testLamb<int, 4>(4); // Error C2062 !!
int f2 = testLamb(5); // OK!
  • *"which have two specializations"*, `data + max` is valid for both cases as `data + 0` is `data` (assuming no strange overloads for `T::operator+(int) /*const*/`) ;-) – Jarod42 Aug 10 '21 at 10:02
  • Notice that you want to call a lambda template, whereas in the linked (misnamed) question OP wants to call a template variable initialized by a lambda (non-template). – Jarod42 Aug 10 '21 at 10:05

1 Answers1

5

It is not the class/variable which is template, but its operator:

testLamb.operator()<int, 4>(4);
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • However, I tried following code and this failed compiling on gcc12.1 and clang14.0. `template int f(){ auto testLamb = [](){ return max; }; return testLamb.operator()();}`. Why? – Kai Gu Aug 13 '22 at 04:23
  • 1
    @KaiGu: It would be `testLamb.template operator()()`. [Demo](https://godbolt.org/z/c8av5e11P) – Jarod42 Aug 13 '22 at 07:50