C++中的变量参数函数问题

Fre*_*urn 0 c++ variadic-functions

我正在尝试在C++中创建一个可变长度函数(显然,heh),而我现在所拥有的功能,但仅适用于第一个参数.如果有人可以请让我知道如何使用所有通过的论点,我会非常感激.

码:

void udStaticObject::accept( udObjectVisitor *visitor, ... )
{
    va_list marker;
    udObjectVisitor *i = visitor;
    va_start( marker, visitor );
    while( 1 )
    {
        i->visit_staticObject( this );
//the if here will always go to the break immediately, allowing only 
//one argument to be used
        if( ( i = va_arg( marker, udObjectVisitor* ) ) )
            break;
    }
    va_end( marker );
}
Run Code Online (Sandbox Code Playgroud)

根据我过去发布的帖子以及我提供的任何帮助帖子,可能会提供一些我没有提供的信息,您需要知道这些信息才能提供帮助.如果我忘了什么,我会提前道歉,请告诉我您需要知道的内容,以便我提供相关信息.

Jam*_*lis 5

如果使用可变参数函数,则需要一些方法来告诉函数传递了多少参数.例如,printf()和朋友一起使用包含每个传递参数的格式说明符的格式化字符串,并且它们计算格式说明符的数量以确定传递了多少个参数.

传递指针列表时,可以通过将空指针作为最后一个参数传递来"更简单地"完成此操作.这样,您只需读取参数,直到到达空指针.

However, you should seriously consider not using a variadic function for this. You can accomplish the same behavior by taking a vector of pointers as a parameter and iterating over the contents of that vector. There are a number of reasons why this is superior to using a variadic function:

  • Variadic functions have absolutely no type safety. You lose any and all type information about the arguments when you pass them to a variadic function, so for example, a caller of your function could pass a numeric value instead of a pointer and you'd never be able to tell inside of your function.

  • 使用可变参数解决方案,调用者必须正确指示参数的数量.如果调用者在末尾省略了空指针(或者错误地告诉你函数有多少参数)并且你尝试读取的参数多于传递的参数,那么你最终会得到未定义的行为.现在你可能会说"好吧,这不难忘记",但不可避免的是,有人会忘记或搞砸它并调试这类问题是一种殴打.

  • 采用向量并迭代其内容的解决方案实现起来更简单,更易于调试,并且在C++中更加惯用.

如果在使用可变参数函数和不使用可变参数函数之间存在选项,则不应使用可变参数函数(我承认,我从未在我编写的任何C++代码中编写可变参数函数,尽管我在C)写了一些.