Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 lambda in decltype

For the following code:

auto F(int count) -> decltype([](int m) { return 0; })  {                                                                    return [](int m) { return 0; };                                   } 

g++ 4.5 gives the errors:

test1.cpp:1:32: error: expected primary-expression before 'int' test1.cpp:1:32: error: expected ')' before 'int' 

What is the problem? What is the correct way to return a lambda from a function?

like image 966
HighCommander4 Avatar asked Jan 31 '11 00:01

HighCommander4


People also ask

What is lambda function in C++11?

In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.

What is generic lambda?

Conceptually, a generic lambda is equivalent to a function object with a templatized function-call operator method: struct LambdaClosureType { ... template<template-params> ret operator()(params) const { ... } .... };

How do you declare lambda in C++?

Creating a Lambda Expression in C++auto greet = []() { // lambda function body }; Here, [] is called the lambda introducer which denotes the start of the lambda expression. () is called the parameter list which is similar to the () operator of a normal function.

What is a lambda capture?

This means when the lambda is created, the lambda captures a constant copy of the outer scope variable, which means that the lambda is not allowed to modify them. In the following example, we capture the variable ammo and try to decrement it.


2 Answers

You cannot use a lambda expression except by actually creating that object- that makes it impossible to pass to type deduction like decltype.

Ironically, of course, the lambda return rules make it so that you CAN return lambdas from lambdas, as there are some situations in which the return type doesn't have to be specified.

You only have two choices- return a polymorphic container such as std::function, or make F itself an actual lambda.

auto F = [](int count) { return [](int m) { return 0; }; }; 
like image 115
Puppy Avatar answered Oct 11 '22 14:10

Puppy


something like this fits your needs?

#include <functional>  std::function<int(int)> F(int count) {                                                                    return [](int m) { return 0; };                                   } 
like image 37
Andriy Tylychko Avatar answered Oct 11 '22 14:10

Andriy Tylychko