0

I'm trying to understand why this piece of code will not compile:

void test_fff()
{
    auto f1 = [](int x) {return x;};
    decltype(f1) f2 = [](int y) {return y;};
}

This is the compile error I'm getting:

error: conversion from 'test_fff()::<lambda(int)>' to non-scalar type 'test_fff()::<lambda(int)>' requested 177 | decltype(f1) f2 = [](int y) -> int {return y;};

I'm using g++ 10.2.0 with -std=c++17

However, this code compiles just fine:

void test_fff()
{
    FFF<decltype(2)>::foo(2);

    std::function<int (int)> f1 = [](int x) {return x;};
    decltype(f1) f2 = [](int y) {return y;};
}

What's the difference between the two?

user1912594
  • 365
  • 3
  • 10
  • see https://stackoverflow.com/questions/7951377/what-is-the-type-of-lambda-when-deduced-with-auto-in-c11 and https://stackoverflow.com/questions/3161219/what-is-the-type-of-a-lambda-function – NathanOliver Oct 08 '20 at 21:42
  • 1
    Every lambda is a different type; also `auto f1 = []{}; decltype(f1) f2 = []{};` doesn't works because the first `[]{}` and the second `[]{}` are different types. – max66 Oct 08 '20 at 22:00

1 Answers1

1

What's the difference between the two?

The difference between the two is that in the first case:

auto f1 = [](int x) {return x;};
decltype(f1) f2 = [](int y) {return y;};

The type of f1 (and thus of decltype(f1), so the type of f2) is the type of the first lambda and, taking into account that every lambda is of different type, you can't assign the second lambda to a variable of the type of the first lambda.

In the second case:

std::function<int (int)> f1 = [](int x) {return x;};
decltype(f1) f2 = [](int y) {return y;};

The type of f1 (and thus of decltype(f1), so the type of f2) is std::function<int(int)>, that isn't the type of the first or second lambda, but is compatible with both. Compatible in the sense that both lambdas can be assigned to a std::function<int(int)>.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
max66
  • 65,235
  • 10
  • 71
  • 111