2011-12-27 71 views
8

我现在使用此代码:(用户不能打电话argc与任意数量的参数的函数)获取参数的数量

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

    // ... 

但它是有点丑陋和限制有没有更好的方法来做到这一点?

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

+0

UMH的参数类型并不总是一样的... – 2011-12-27 13:18:13

+1

@ JohannesSchaub - litb我认为这意味着他们总是相同这些例子:'Foo'作为返回值,'Bar'作为所有参数。 – 2011-12-27 13:33:37

回答

12

清洁版本@保罗的回答,可与实际物体:

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

下面将任何参数数量的工作,但接受任意参数类型:

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时,这会给你一个编译错误。的