#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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With