我想知道是否有方法在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」應該返回什麼? –