yrHeTateJlb Asked:2020-12-20 19:52:23 +0800 CST2020-12-20 19:52:23 +0800 CST 2020-12-20 19:52:23 +0800 CST 函数参数的数量 772 最近有一个问题是关于如何用给定类型的 n 个参数声明一个函数。我有相反的问题。如何找到函数的参数数量? #include <iostream> void foo(float, int){ } int main(){ std::cout << doTemplateMagic(foo); //2 } c++ 3 个回答 Voted Unick 2020-12-20T20:13:22+08:002020-12-20T20:13:22+08:00 您可以使用具有可变数量参数的模板: #include <iostream> template <typename R, typename ... Types> constexpr size_t getArgumentCount( R(*f)(Types ...)) { return sizeof...(Types); } //---------------------------------- // Test it out with a few functions. //---------------------------------- void foo(int a, int b, int c) { } int bar() { return 0; } int baz(double) { return 0; } int main() { std::cout << getArgumentCount(foo) << std::endl; std::cout << getArgumentCount(bar) << std::endl; std::cout << getArgumentCount(baz) << std::endl; return 0; } 结论: 3 0 1 或者使用这个方法: template <typename R, typename ... Types> constexpr std::integral_constant<unsigned, sizeof ...(Types)> getArgumentCount( R(*f)(Types ...)) { return std::integral_constant<unsigned, sizeof ...(Types)>{}; } // Guaranteed to be evaluated at compile time size_t count = decltype(getArgumentCount(foo))::value; 或者 // Most likely evaluated at compile time size_t count = getArgumentCount(foo).value; 来源:https ://stackoverflow.com/questions/36797770/get-function-parameters-count Best Answer Abyx 2020-12-20T20:21:12+08:002020-12-20T20:21:12+08:00 例如 Boost.TypeTraits #include <type_traits> #include <boost/type_traits.hpp> void f(int, char) {} int n = boost::function_traits<std::remove_pointer_t<decltype(&f)>>::arity; int3 2020-12-20T20:39:46+08:002020-12-20T20:39:46+08:00 我会批评其余的答案,引用: “不要尝试编写辅助代码来检测 PMF/PMD 并对其进行调度——这绝对是一场噩梦。PMF 类型是迄今为止核心语言中最差的类型。” 使用Boost.CallableTraits #include <type_traits> #include <boost/callable_traits.hpp> namespace ct = boost::callable_traits; int main() { auto lamda = [](int, float&, const char*){}; using lam = decltype(lamda); static_assert(std::tuple_size_v<ct::args_t<lam>> == 3); }
您可以使用具有可变数量参数的模板:
结论:
或者使用这个方法:
或者
来源:https ://stackoverflow.com/questions/36797770/get-function-parameters-count
例如 Boost.TypeTraits
我会批评其余的答案,引用:
使用Boost.CallableTraits