获取函数指针的参数计数
Getting argument count of a function pointer
我现在使用以下代码:
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
)。有更好的方法吗?
注意:返回类型和实参类型总是相同的。我知道我可以使用模板来接受任何类型,但我不需要它。
@Paolo答案的更清晰版本,可用于实际对象:
template<class R, class... Args>
constexpr unsigned arity(std::function<R(Args...)> const&){
return sizeof...(Args);
}
以下将适用于任何实参类型,但接受任意实参类型:
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时,这将给您一个编译错误。
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类