Steve Lorimer
Steve Lorimer

Reputation: 28659

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

I'm sure I've seen this described before but can't for the life of me find it now.

Given a class with a member function of some form, eg:

int Foo::Bar(char, double)

How can I use a template and various specialisations to deduce the constituent types, eg:

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

Such that when I instantiate Types with my above member function, eg:

Types<&Foo::Bar>

it resolves to the correct specialisation, and will declare the relevant typedefs?

Edit:

I'm playing around with fast-delegates with the callback statically bound to a member function.

I have the following mockup which I believe does statically bind to the member function:

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

However - how to get this as a specialisation in the manner above?

Upvotes: 3

Views: 226

Answers (1)

kennytm
kennytm

Reputation: 523214

You've almost got it, except that extra MemFunc, which is not part of the type.

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

Nevertheless, you cannot use

Types<&Foo::Bar>

because Foo::Bar is a member function pointer, not the type of it. You'll need some compiler extensions to get the type in C++03, e.g. typeof in gcc or Boost.Typeof:

Types<typeof(&Foo::Bar)>

or upgrade to C++11 and use the standard decltype:

Types<decltype(&Foo::Bar)>

Upvotes: 4

Related Questions