获取函数指针的参数计数

时间:2011-12-27 13:12:03

标签: c++ c++11

我现在正在使用此代码:

    size_t argc(std::function<Foo()>)
    { return 0; }

    size_t argc(std::function<Foo(Bar)>)
    { return 1; }

    size_t argc(std::function<Foo(Bar, Bar)>)
    { return 2; }

    size_t argc(std::function<Foo(Bar, Bar, Bar)>)
    { return 3; }

    // ...

但它有点丑陋且有限(用户不能使用具有任意数量参数的函数调用argc。)有更好的方法吗?

注意:返回类型和参数类型始终相同。我知道我可以使用模板来接受任何类型,但我不需要它。

2 个答案:

答案 0 :(得分:12)

@ Paolo答案的清洁版,可用于实际对象:

template<class R, class... Args>
constexpr unsigned arity(std::function<R(Args...)> const&){
  return sizeof...(Args);
}

答案 1 :(得分:5)

以下内容适用于任何arity,但接受任意参数类型:

template <typename T>
struct arity
{
};

template <typename... Args>
struct arity<std::function<Foo(Args...)>>
{
    static const int value = sizeof...(Args);
};

如果你真的想将你的参数类型约束为Foo(Bar, Bar, ...)类型的函数,那么你可以这样做:

template <typename T>
struct arity
{
};

template <typename... Args>
struct const_tuple
{
};

template <>
struct const_tuple<>
{
    struct unsupported_function_type { };
};

template <typename... Args>
struct const_tuple<Bar, Args...>
{
    typedef typename const_tuple<Args...>::unsupported_function_type unsupported_function_type;
};

template <typename... Args>
struct arity<std::function<Foo(Args...)>> : public const_tuple<Args...>::unsupported_function_type
{
    static const int value = sizeof...(Args);
};

每当使用不支持的函数类型调用arity时,这将给出编译错误。

相关问题