我試圖重新編碼一些相當醜陋的模板編碼。使用模板編碼靜態實例方法trampoline函數
僅供參考,原來是在這裏:https://codereview.stackexchange.com/questions/69545/recode-c-c-trampoline-function-macros-using-templates
class Final : Base
{
void Foo(){...}
void Bar(){...}
static void init(){
// register_method populates a table of "extern C" function pointers.
register_method("foo", & FooHandler);
register_method("bar", & BarHandler);
}
:
// trampolines
static void FooHandler(void* pInstance) {
Final* f = reinterpret_cast<Final*>(pInstance);
f->Foo();
}
static void BarHandler(void* pInstance) {
Final* f = reinterpret_cast<Final*>(pInstance);
f->Bar();
}
}
我與CPython的(C庫)代碼的接口。 Python運行時看到「myInst.foo」查找「foo」的表中,並調用:
Final::FooHandler(pointer_to_myInst);
(注意有可能強制轉換一個靜態方法來C函數指針)
FooHandler蹦牀到Final的正確實例的Foo方法。
實際上,句柄並不那麼幹淨,並且有很多方法都需要相同的處理程序(但具有不同的函數地址)。
我試圖抽象處理機制引入一個基類,像這樣:
class Final : Base<Final>
{
void Foo(){...}
void Bar(){...}
static void init(){
// register_method populates a table of "extern C" function pointers.
register_method("foo", & Foo, Handler< &Foo>);
register_method("bar", & Bar, Handler< &Bar>);
}
:
}
class Base<Final>
{
typedef void (Final::*FuncSig)(void);
typedef void (Final::*HandlerSig)(void*); // takes 1 pvoid param
void register_method(std::string name, FuncSig meth, HandlerSig handler) {
...
}
// generic trampoline
template< Sig sig>
static void Handler(void* pInstance) {
Final* f = reinterpret_cast<Final*>(pInstance);
f ->* sig();
}
}
我目前陷在編譯器錯誤(http://ideone.com/vOtbcD),所以我甚至不能確定是否技術是有效的。
有沒有辦法做到這一點,或者這只是其中一個真正需要宏的地方?
僅供參考,原來是在這裏:https://codereview.stackexchange.com/questions/69545/recode-c-c-trampoline-function-macros-using-templates
可以看出,原來的用途,而難看的宏。
好對於初學者'Base'不是模板類,你需要使用關鍵字'template'。您可能還想閱讀['std :: function'](http://en.cppreference。com/w/cpp/utility/functional/function)和['std :: bind'](http://en.cppreference.com/w/cpp/utility/functional/bind)。 – 2014-11-14 16:06:57