How to determine number of function arguments dynamically

Posted by Kam on Stack Overflow See other posts from Stack Overflow or by Kam
Published on 2014-06-01T06:46:03Z Indexed on 2014/06/01 9:25 UTC
Read the original article Hit count: 113

Filed under:

I have the following code:

#include <iostream>
#include <functional>

class test
{
public:
    typedef std::function<bool(int)> Handler;

    void handler(Handler h){h(5);}
};

class test2
{
public:
      template< typename Ret2, typename Ret, typename Class, typename Param>
      inline Ret2 MemFn(Ret (Class::*f)(Param), int arg_num)
      {
          if (arg_num == 1)
              return std::bind(f, this, std::placeholders::_1);
      }

    bool f(int x){ std::cout << x << std::endl; return true;}
};

int main()
{
    test t;
    test2 t2;

    t.handler(t2.MemFn<test::Handler>(&test2::f, 1));


    return 0;
}

It works as expected.

I would like to be able to call this:

t.handler(t2.MemFn<test::Handler>(&test2::f));

instead of

t.handler(t2.MemFn<test::Handler>(&test2::f, 1));

Basically I need MemFn to determine in runtime what Handler expects as the number of arguments.

Is that even possible?

© Stack Overflow or respective owner

Related posts about c++11