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

2024-01-23

我确信我以前见过这种描述,但现在我一辈子都找不到它。

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

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?

Edit:

我正在使用快速委托,并将回调静态绑定到成员函数。

我有以下模型,我相信它静态绑定到成员函数:

#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();
}

但是 - 如何以上述方式将其作为专业化?


你几乎已经得到它了,除了额外的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;
};

尽管如此,你cannot use

Types<&Foo::Bar>

因为 Foo::Bar 是一个成员函数指针,而不是它的类型。您需要一些编译器扩展来获取 C++03 中的类型,例如typeof in gcc http://gcc.gnu.org/onlinedocs/gcc/Typeof.html or Boost.Typeof http://www.boost.org/doc/libs/1_48_0/doc/html/typeof.html:

Types<typeof(&Foo::Bar)>

或升级到 C++11 并使用标准decltype http://en.wikipedia.org/wiki/Decltype:

Types<decltype(&Foo::Bar)>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用模板专门化来查找成员函数参数类型等? 的相关文章

随机推荐