Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is auto not allowed in lambda parameter?

Tags:

c++

lambda

auto

When I write a lambda definition with the following signature:

auto lambda = [&] (auto i){


};

I get the following compiler error:

error: 'auto' not allowed in lambda parameter

When I change the type from auto to int, the error disappears.

I am not sure why the compiler can deduce the type of a lambda, but not its parameter type, which should be known to it at the time of the invocation of the lambda?

I am trying to understand the reasoning behind this restriction.

like image 655
user9196120 Avatar asked Feb 06 '18 22:02

user9196120


1 Answers

I am not sure why the compiler can deduce the type of a lambda, but not its parameter type, which should be known to it at the time of the invocation of the lambda?

It can, but only since C++14.

auto lambda = [&] (auto i) { };

This code is perfectly legal since C++14 and called generic lambda.

Unfortunately, generic lambdas are not available before C++14, so, if you need to use them, C++14 support is required.

like image 125
Edgar Rokjān Avatar answered Sep 24 '22 23:09

Edgar Rokjān