Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"auto" variable used in lambda in its own initializer

Today I found this code

#include <cstdio>  auto terminal = [](auto term)            {                                            return [=] (auto func)                  {                                            return terminal(func(term));     }; }; 

Surprisingly, GCC accepts it. Clang rejects it because it uses terminal in its own intializer and is declared auto.

I was expecting the error that clang gave, but is it actually ill-formed? Or must the code be accepted?

like image 858
Johannes Schaub - litb Avatar asked Sep 05 '14 20:09

Johannes Schaub - litb


People also ask

Is it mandatory to initialise an auto variable at the time of declaration?

It is necessary to initialize the variable when declaring it using the auto keyword.

How to initialize auto variable in C++?

You can initialize any auto variable except function parameters. If you do not explicitly initialize an automatic object, its value is indeterminate. If you provide an initial value, the expression representing the initial value can be any valid C or C++ expression.

What is auto variable in Cpp?

The auto keyword is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.


1 Answers

I think this runs into §7.1.6.4 [dcl.spec.auto]/p11:

If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed.

You need the type of terminal to determine the type of the id-expression terminal in return terminal(func(term)); (edited, hat tip @Richard Smith), but at the point of that expression you can't deduce the type of terminal yet.

like image 98
T.C. Avatar answered Oct 08 '22 09:10

T.C.