【发布时间】:2012-07-18 19:00:22
【问题描述】:
我有几个非常相似的功能:
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();
}
我已经阅读 C++ 模板几个小时了,我确信可以摆脱这些函数并用模板替换它们。我设想最终结果将是这样的:
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 ...;
我知道有人问过类似的问题,但我在上述模板中找不到模板示例。
2012 年 7 月 21 日更新
模板:
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();
}
用法:
audio->PrototypeTemplate()->Set("Volume", v8::FunctionTemplate::New(&jsFunctionTemplate<Audio>));
现在,如果我能弄清楚如何将&Audio::volume 传递给模板,那我就成功了。
2012 年 7 月 24 日更新
请参阅我的回答,了解我是如何解决这个问题的。
【问题讨论】: