0

I've read the previous question here but it seems a bit unrelated. C++ lambda, when it captured nothing, is fine to be an argument of the v8::FunctionTemplate. But when it captured something I needed, compiler started to complain:

error: no matching function for call to 'v8::FunctionTemplate::New( BaseContext::New(const v8::Arguments&)::<lambda(const v8::Arguments&)>)

And here is the test code:

int a = 3;

Local<FunctionTemplate> failed = FunctionTemplate::New(
[=, a](const Arguments& args)-> Handle<Value>
{   
    a = a+a;
}); 


Local<FunctionTemplate> success = FunctionTemplate::New(
[](const Arguments &args) -> Handle<Value>
{
    int a = 3;
});

I want to use the lambda feature because it's no reason to define small static functions which will actually become callbacks in another function. But the only difference between capturing and none capturing really bothers me, and the error message seems caused by the lambda itself, no matter whether it capture things or not.

1 Answer 1

1

This is because a lambda that does not capture can be treated as a normal function pointer, whereas a lambda that captures cannot.

The first argument to FunctionTemplate::New is an InvocationCallback, which is just a function pointer.

typedef Handle<Value> (*InvocationCallback)(const Arguments& args);

For example, both are valid std::function objects:

// Compiles
function<Handle<Value> (const Arguments&)> cb1 = [](const Arguments &args) -> Handle<Value> {
    int a = 3;
};

// Compiles
function<Handle<Value> (const Arguments&)> cb2 = [=](const Arguments &args) -> Handle<Value> {
    int a = 3;
};

But only the first is a valid callback:

// Compiles
InvocationCallback cb1 = [](const Arguments &args) -> Handle<Value> {
    int a = 3;
};

// Does not compile
InvocationCallback cb2 = [=](const Arguments &args) -> Handle<Value> {
    int a = 3;
};
Sign up to request clarification or add additional context in comments.

2 Comments

Well, I think my plan to avoid small functions everywhere is broken... at least need to find better way to do that. Anyway, thanks you answer, it's useful and clear.
@snowmantw What is it that you want to pass in via the capture? You might be able to use the data argument for FunctionTemplate instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.