如何动态确定函数参数的数量

时间:2014-06-01 06:46:04

标签: c++11

我有以下代码:

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

它按预期工作。

我希望能够称之为:

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

而不是

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

基本上我需要MemFn在运行时确定Handler期望的参数数量。

这甚至可能吗?

1 个答案:

答案 0 :(得分:0)

您可以创建一些type_traits来获取您的信息,例如:

template <typename T> struct function_trait;

template <typename Ret, typename ... Args>
struct function_trait<std::function<Ret(Args...)>>
{
    static constexpr std::size_t args_count = sizeof...(Args);
};

因此您的方法可能如下所示:

template<typename Ret2, typename Ret, typename Class, typename Param>
inline Ret2 MemFn(Ret (Class::*f)(Param))
{
    if (function_trait<Ret2>::args_count == 1)
        return std::bind(f, this, std::placeholders::_1);
    throw std::runtime_error("invalid number of arguments");
}