<分区>
我想知道 C++11 中是否有获取函数参数个数的方法?
例如,对于函数 foo
,我希望 argCount
为 3。
void foo(int a, int b, int c) {}
int main() {
size_t argCount = MAGIC(foo);
}
<分区>
我想知道 C++11 中是否有获取函数参数个数的方法?
例如,对于函数 foo
,我希望 argCount
为 3。
void foo(int a, int b, int c) {}
int main() {
size_t argCount = MAGIC(foo);
}
最佳答案
您可以使用可变函数模板获取该信息。
#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
在 http://ideone.com/oqF8E8 查看它的工作情况.
更新
巴里建议使用:
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;
关于c++ - 获取函数参数个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36797770/