动态使用变量参数函数

Using variable argument functions dynamically

本文关键字:参数 函数 变量 动态      更新时间:2023-10-16

我一直在寻找答案,但我不确定,变量参数函数是在编译时还是动态创建或解析的?例如,是否可以在运行时获取用户的输入,然后根据输入的输入数调用函数?谢谢

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.