Search code examples
c++variadic-functionsfunction-parameterstdlist

Variadic function declaration VS a function taking a list


While designing a class or a function, which way, that is shown below, is better and why?

class Container {

    //Provide this functionality??
    void addItemVariadic(const Value& val, ...);

    //Or provide this functionality??
    void addItemList(const list<Value>& vals);

};

Is it better to provide a function like addItemVariadic(..), or addItemList(..)?

Or is it better to provide a set of such functions, like further taking some iterators, or is it better to limit the functionality, like just taking a list?


Solution

  • Using variadic functions is dangerous

    If you ever pass a variable which has not the appriopriate type, it will crash at run time, when calling the function.

    On the contrary if you use a std::list, it won't compile simply, and you avoid a crash.

    Btw: I advice you to use std::vector instead of std::list in this case.

    Edit1 Possible Dupplicate Question. with a nice solution using operator << to inputs all the parameters in one shot.

    Edit2 So as to choose between different std::containers, there is a choose-graph as answer to this question. This graph addresses at C++03, it doesn't cover the new containers introduced in C++1.