【问题标题】:How can I use template specialisation to find member function argument types etc?如何使用模板特化来查找成员函数参数类型等?
【发布时间】:2012-01-19 20:28:34
【问题描述】:

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

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

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 world\n";
  }
};

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

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

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

【问题讨论】:

    标签: c++ templates metaprogramming


    【解决方案1】:

    你几乎得到了它,除了额外的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 中的类型,例如typeof in gccBoost.Typeof:

    Types<typeof(&Foo::Bar)>
    

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

    Types<decltype(&Foo::Bar)>
    

    【讨论】:

    • 不幸的是,这个练习的重点是我想静态绑定到一个成员函数,这样优化器就可以通过函数指针边界进行优化,可以这么说。使用 decltype 可以实现这一点吗?
    • decltype 只返回对象的类型,而不是指针本身。您是否要创建fast delegate
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 2013-09-24
    相关资源
    最近更新 更多