문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top