Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failing to deduce type from lambdas in the initializer list

#include <functional>
#include <iostream>

namespace{
//const std::function< void( const int ) > foo[] =
const auto foo[] =
{
  []( const int v ){ std::cout<<v<<std::endl; },
  []( const int v ){ std::cout<<v/2<<std::endl; },
  []( const int v ){ std::cout<<v/3<<std::endl; },
};

}

int main()
{
  foo[1](5);
}

The above example fails to compile (using g++ 4.6.1) with next error message:

error: unable to deduce 'const std::initializer_list<const auto> []' from '{{}, {}, {}}'

The commented line works fine (without specifying the function type).

Is this a quirk of g++? Or is there anything in the standard that tells the above should not compile?

like image 459
BЈовић Avatar asked Dec 28 '22 00:12

BЈовић


2 Answers

You can't do this. Each lambda has an unique, unrelated type. If you want a collection of lambdas, you have to erase the type with std::function:

std::function<void(int)> foo[] = {
    [](int) { ... },
    [](int) { ... },
    ...
};

Even in

auto f1 = []{};
auto f2 = []{};

the two types are different.

like image 148
Cat Plus Plus Avatar answered Feb 02 '23 23:02

Cat Plus Plus


In addition to what others say about the lambdas having unique types, you are not allowed to use auto as the specifier in an array variable declaration. Even the following is ill-formed

auto x[] = { 1, 2, 3 }; // 'auto' disallowed
like image 26
Johannes Schaub - litb Avatar answered Feb 02 '23 23:02

Johannes Schaub - litb