1
votes

Do lambda function have a signature so that I can pass them around?

template<class Fn> 
HRESULT foreach(Fn _fuction)
{

}


object->foreach(
    [param1, param2] (int item) 
    {
    }
);

object->foreach(
    [param1, param2, param3] (int item) 
    {
    }
);

I want to use a typedef function instead of templates, I think the type of the function will strict the formal parameters but will allow captured list to vary.

can I use typedef instead of templates to pass lambda functions around?

something like:

typedef void (*Fn)(int);

but allows lambda not function pointer.

I tried using std::fuction but seems not working.

2
For what it's worth, using a template type isn't a bad solution (depending on context, of course) since there is some overhead involved in converting to function. - dlf
I swear this exact question was asked like a couple days ago. - chris
Can you show how you tried using std::function? seems not working isn't a particularly useful description. - Praetorian

2 Answers

1
votes

The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed non- union class type — called the closure type ...

(C++11 §5.1.2/3, emphasis mine)

My reading of this is that even if two lambda-expressions have the same parameter list, return type, and capture list, they nevertheless have different types.

auto f = []{};
typedef decltype(f) lambda_type;
void g(lambda_type lambda) { lambda(); }
int main() {
    g(f);    // OK
    g([]{}); // error: type mismatch
}

So no, what you are trying to do cannot be done. As others have suggested, try using std::function, or retain the template (what's wrong with templates, anyway?)

0
votes

The actual type of a lambda is unspecified. But they are convertible to function; in your case, std::function<void(int)> (void is the return type, the parameter types go in the parentheses).