我想知道是否有方法在C++ 11中获取函数的参数数量?获取函数参数计数
例如,对于功能foo
我想argCount
为3。
#include <iostream>
void foo(int a, int b, int c)
{
}
int main()
{
size_t argCount=MAGIC(foo);
return 0;
}
在此先感谢。
我想知道是否有方法在C++ 11中获取函数的参数数量?获取函数参数计数
例如,对于功能foo
我想argCount
为3。
#include <iostream>
void foo(int a, int b, int c)
{
}
int main()
{
size_t argCount=MAGIC(foo);
return 0;
}
在此先感谢。
您可以通过使用一个可变参数函数模板获得这些信息。
#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;
是的,它可以很容易地完成:
#include <cstddef>
#include <iostream>
template <class R, class... ARGS>
struct function_ripper {
static constexpr size_t n_args = sizeof...(ARGS);
};
template <class R, class... ARGS>
auto constexpr make_ripper(R (ARGS...)) {
return function_ripper<R, ARGS...>();
}
void foo(int, double, const char*);
void check_args() {
constexpr size_t foo_args = decltype(make_ripper(foo))::n_args;
std::cout << "Foo has " << foo_args << " arguments.\n";
}
为此目的应该是有益的? –
@πάνταῥεῖ,我知道至少有一个这样的应用程序,在重元编程 – SergeyA
如果有几个重载在参数数量上有所不同,那么“MAGIC”应该返回什么? –