动态使用变量参数函数
Using variable argument functions dynamically
我一直在寻找答案,但我不确定,变量参数函数是在编译时还是动态创建或解析的?例如,是否可以在运行时获取用户的输入,然后根据输入的输入数调用函数?谢谢
void func(int num_args, ...)
{
....
}
函数
参数的数量和类型在编译时解析,值在编译时或运行时解析,具体取决于它们的值是否constexpr
相似。
考虑一下如何在运行时使用收集的任意数量的变量调用函数。这种构造没有C++语法。
相反,您应该做的是使用类似的东西 std::vector
.具有一些虚拟函数的示例:
void func (const std::vector<std::string>& args);
std::string getarg();
bool haveargs();
int main() {
std::vector<std::string> args;
while (haveargs()) {
args.push_back(getarg());
}
func(args);
}
变量参数函数是在编译时还是动态创建或解析的?
C++ 不是 JIT 编译语言(通常),因此无法在语言级别创建运行时函数。
是否可以在运行时获取用户的输入,然后根据输入的输入数调用函数?
当然,但请确保进行错误检查!
总而言之,我建议不要使用 C 风格的可变参数函数,而是针对每个单独的参数类型将其拆分为不同的函数。可变参数函数充满危险,容易搞砸。
它们是在编译时创建的。 而不是传递离散参数列表,而是使用 va_start
宏获取包装在返回的va_list
结构中的堆栈地址。 va_start
宏使用传递给函数的最后一个定义的参数,因此通常使用它来提供一种机制来确定参数的实际运行时数及其类型。 例如,printf
需要一个格式字符串,因为其他参数的大小可能不同,而下面的代码使用简单的计数,因为它只需要整数。
int average(int count, ...)
{
va_list valist;
int total;
int i;
// Initialize valist for number of arguments specified by count.
va_start(valist, count);
// Get the total of the variable arguments in the va_list.
for(total = 0, i = 0; i < num; i++)
{
// Use va_arg to access the next element in the va_list
// by passing the list and the type of the next argument.
total += va_arg(valist, int);
}
// Release the va_list memory.
va_end(valist);
return total/count;
}
// Using the function: pass the number of arguments
// then the arguments themselves.
printf("The average is %d.", average(3, 1, 2, 3));
Output: The average is 2.
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类