如何使用模板专业化来查找成员函数参数类型等

How can I use template specialisation to find member function argument types etc?

本文关键字:函数 成员 参数 类型 查找 何使用 专业化      更新时间:2023-10-16

我肯定以前见过这样的描述,但现在我一辈子都找不到。

给定一个具有某种形式的成员函数的类,例如:

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>

它决定了正确的专业化,并将宣布相关的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 worldn";
  }
};
int main()
{
  typedef cb < app, &app::cb > app_cb;
  app* foo = new app;
  app_cb f ( foo );
  f();
}

然而,如何以上述方式将其作为专业化?

除了额外的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>

因为Foo::Bar是一个成员函数指针,而不是它的类型。您需要一些编译器扩展才能在C++03中获得类型,例如gcc或Boost中的typeof。Typeof:

Types<typeof(&Foo::Bar)>

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

Types<decltype(&Foo::Bar)>