I have several very similar functions:
v8::Handle<v8::Value> jsAudioPlay(const v8::Arguments &args) {
Audio *audio = static_cast<Audio*>(args.This()->GetPointerFromInternalField(0));
if (audio != NULL) audio->play(get(args[0], 0));
return args.This();
}
v8::Handle<v8::Value> jsAudioPause(const v8::Arguments &args) {
Audio *audio = static_cast<Audio*>(args.This()->GetPointerFromInternalField(0));
if (audio != NULL) audio->pause();
return args.This();
}
v8::Handle<v8::Value> jsAudioLoop(const v8::Arguments &args) {
Audio *audio = static_cast<Audio*>(args.This()->GetPointerFromInternalField(0));
if (audio != NULL) audio->loop(get(args[0], -1));
return args.This();
}
v8::Handle<v8::Value> jsAudioVolume(const v8::Arguments &args) {
Audio *audio = static_cast<Audio*>(args.This()->GetPointerFromInternalField(0));
if (audio != NULL) audio->volume(get(args[0], 1.0f));
return args.This();
}
And I've been reading about C++ templates for hours and I'm convinced that it's possible to get rid of these functions and replace them with templates. I envision the end result will be something like:
typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
template <class T> InvocationCallback FunctionWrapper ...;
template <class T> FunctionWrapper FunctionReal ...;
template <class T, class arg1> FunctionWrapper FunctionReal ...;
template <class T, class arg1, class arg2> FunctionWrapper FunctionReal ...;
I realize similar questions have been asked, but I can't find an example of a template within a template like the above.
Update on 7/21/2012
Template:
template <class T> v8::Handle<v8::Value> jsFunctionTemplate(const v8::Arguments &args) {
T *t = static_cast<T*>(args.This()->GetPointerFromInternalField(0));
if (t != NULL) t->volume(args[0]->NumberValue());
return args.This();
}
Usage:
audio->PrototypeTemplate()->Set("Volume", v8::FunctionTemplate::New(&jsFunctionTemplate<Audio>));
Now if I could only figure out how to pass &Audio::volume
to the template, I'll be in business.
Update on 7/24/2012
Refer to my answer for how I solved this.