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?
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)>
.