我想知道在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中查看它的工作方式。
更新
Barry建议使用:
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;
integral_constant
而不是 size_t
(请参见Columbo在重复问题上的回答) - Barryintegral_constant
的目的是为了简化struct get_arity
的实现。对于像我在这里展示的自由函数,这不会增加任何额外的价值。如果我漏掉了什么微妙的东西,请告诉我。 - R Sahu没问题,这可以很容易地完成:
#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";
}
void f(int);
void f(int, int);
std::cout << MAGIC(f); // what should this print??
MAGIC
应该返回什么? - Baum mit Augen