c++ - 如何使用模板特化来查找成员函数参数类型等?

标签 c++ templates metaprogramming

我敢肯定我以前见过这个描述,但现在找不到了。

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

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?

编辑:

我正在使用快速委托(delegate),回调静态绑定(bind)到成员函数。

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

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

但是,您不能使用

Types<&Foo::Bar>

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

Types<typeof(&Foo::Bar)>

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

Types<decltype(&Foo::Bar)>

关于c++ - 如何使用模板特化来查找成员函数参数类型等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8932803/

相关文章:

c++ - 将模板类作为 arg 参数传递给 std::bind

c++ - 允许非 const 在包装器模板中转换为 const

Python自动备忘

metaprogramming - Elixir - 通过元编程在模块中定义函数

c++ - 用于基于任务的并行性的通用 c++11 函数包装器

c++ - 如何解决 imgproc.hpp 和 core.hpp 的错误?

c++ - 避免在 ctor 初始化列表中的字符串赋值中重复调用函数

javascript - Handlebars.js 条件语句

ruby - 在模块中定义类访问器的简写

c++ - 什么是段错误?