Reputation: 1621
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.
Upvotes: 0
Views: 1149
Reputation: 161567
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;
};
Upvotes: 1