c++ - 获取函数参数个数

标签 c++ c++11

<分区>

我想知道 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/

相关文章:

c++ - 允许模拟类继承自最终类

c++ - 静态初始化不安全调用的线程安全

c++ - 使用模板参数包代替宏

c++ - 添加参数后“模板参数推导/替换失败”

C++ 复制初始化 + 隐式构造函数调用 = 失败

c++ - strcmp[C++] 错误 : invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]

c++ - 函数退出未遇到返回如何正确处理

C++ 类成员和延迟初始化

c++ - 如何在 Windows XP 上为 Qt 4.7 正确构建 OpenCV 2.3.1?

c++ - 如何在不使用循环的情况下进行排序