Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why lambda returns bool?

I've started learning C++11 and C++14 and i have a question. Why lambda not returns 23?

template<class T>
auto func(T t)
{
    return t;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    auto abc = []()->auto { return func(23); };
    qDebug() << abc; // output: true

    return a.exec();
}
like image 455
Мишаков Максим Avatar asked Dec 13 '17 08:12

Мишаков Максим


People also ask

What is the return type of lambda?

The return type for a lambda is specified using a C++ feature named 'trailing return type'. This specification is optional. Without the trailing return type, the return type of the underlying function is effectively 'auto', and it is deduced from the type of the expressions in the body's return statements.

Which type of object is returned by lambda function in Python?

Lambda functions are syntactically restricted to return a single expression. You can use them as an anonymous function inside other functions. The lambda functions do not need a return statement, they always return a single expression.

Why use lambda?

Why Use Lambda Functions? Lambda functions are used when you need a function for a short period of time. This is commonly used when you want to pass a function as an argument to higher-order functions, that is, functions that take other functions as their arguments.


Video Answer


1 Answers

As @Bathsheba pointed out. You have a typo and don't call the lambda. Now, it's rather obvious that operator<< for qDebug() is not overloaded on the lambda's closure type. So naturally an implicit conversion sequence has to happen. The only available one, and only because your lambda is capture-less, starts with a conversion to a function pointer.

Now, which overload of operator<< can be used to print a function pointer? On the face of it, two likely candidates:

operator<<(bool t)         // Because it prints true, duh
operator<<(const void *p)  // Because pointers :)

So why the bool overload? Because a function pointer is not implicitly convertible to void*. That conversion is conditionally supported, and must be performed with a cast ([expr.reinterpret.cast]/8):

Converting a function pointer to an object pointer type or vice versa is conditionally-supported.

That leaves us only with [conv.bool]:

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool.

like image 200
StoryTeller - Unslander Monica Avatar answered Sep 28 '22 08:09

StoryTeller - Unslander Monica