2012-01-19 41 views
3

我敢肯定,我已经看过这个描述过,但不能为我的生活找到它现在。如何使用模板特化来查找成员函数参数类型等?

考虑一类具有某种形式的成员函数,例如:

int Foo::Bar(char, double) 

如何使用模板和各种特来推断构成类型,如:

template<typename Sig> 
struct Types; 

// specialisation for member function with 1 arg 
template<typename RetType, typename ClassType, etc...> 
struct Types<RetType (ClassType::*MemFunc)(Arg0)> 
{ 
    typedef RetType return_type; 
    typedef ClassType class_type; 
    typedef MemFunc mem_func; 
    typedef Arg0 argument_0; 
    etc... 
}; 

// specialisation for member function with 2 args 
template<typename RetType, typename ClassType, etc...> 
struct Types<RetType (ClassType::*MemFunc)(Arg0, Arg1)> 
{ 
    typedef RetType return_type; 
    typedef ClassType class_type; 
    typedef MemFunc mem_func; 
    typedef Arg0 argument_0; 
    typedef Arg0 argument_1; 
    etc... 
}; 

这样当我用我的上述成员函数实例化类型时,例如:

Types<&Foo::Bar> 

它解析为th e正确的专业化,并将声明相关的typedef?

编辑:

我玩弄快速与代表静态绑定到一个成员函数回调。

我有以下的样机,我相信没有静态绑定的成员函数:

#include <iostream> 

template<class class_t, void (class_t::*mem_func_t)()> 
struct cb 
{ 
    cb(class_t *obj_) 
     : _obj(obj_) 
    { } 

    void operator()() 
    { 
     (_obj->*mem_func_t)(); 
    } 

    class_t *_obj; 
}; 

struct app 
{ 
    void cb() 
    { 
    std::cout << "hello world\n"; 
    } 
}; 

int main() 
{ 
    typedef cb < app, &app::cb > app_cb; 

    app* foo = new app; 
    app_cb f (foo); 
    f(); 
} 

但是 - 如何得到这个在上面的方式专业化?

回答

4

你已经差不多了,除了额外的MemFunc,这不是类型的一部分。

template<typename RetType, typename ClassType, typename Arg0> 
struct Types<RetType (ClassType::*)(Arg0)> // <-- no MemType 
{ 
    typedef RetType return_type; 
    typedef ClassType class_type; 
// typedef MemFunc mem_func;  // <-- remove this line 
    typedef Arg0 argument_0; 
}; 

不过,你不能使用

Types<&Foo::Bar> 

因为富::酒吧是一个成员函数指针,而不是它的类型。你需要一些编译器扩展来获得C++ 03的类型,例如typeof in gccBoost.Typeof

Types<typeof(&Foo::Bar)> 

或升级到C++ 11并使用标准decltype

Types<decltype(&Foo::Bar)> 
+0

遗憾的是这项工作的整点是,我想静态绑定到一个成员函数,所以可以说优化器可以通过函数指针边界进行优化。请问使用decltype可以达到这个目的吗? –

+0

'decltype'只返回对象的类型,而不是指针本身。你是否想要[快速委托](http://www.codeproject.com/KB/cpp/ImpossiblyFastCppDelegate.aspx)? – kennytm

+0

我确实 - 看到编辑的问题。谢谢 –

相关问题