我现在正在使用此代码:
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; }
// ...
Run Code Online (Sandbox Code Playgroud)
但它有点丑陋且有限(用户不能argc
使用具有任意数量参数的函数调用.)有更好的方法吗?
注意:返回类型和参数类型始终相同.我知道我可以使用模板来接受任何类型,但我不需要它.
Xeo*_*Xeo 12
@ Paolo答案的清洁版,可用于实际对象:
template<class R, class... Args>
constexpr unsigned arity(std::function<R(Args...)> const&){
return sizeof...(Args);
}
Run Code Online (Sandbox Code Playgroud)
以下内容适用于任何arity,但接受任意参数类型:
template <typename T>
struct arity
{
};
template <typename... Args>
struct arity<std::function<Foo(Args...)>>
{
static const int value = sizeof...(Args);
};
Run Code Online (Sandbox Code Playgroud)
如果你真的想将你的参数类型约束为类型的函数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);
};
Run Code Online (Sandbox Code Playgroud)
每当使用不支持的函数类型调用arity时,这将给出编译错误.
归档时间: |
|
查看次数: |
1663 次 |
最近记录: |