Variable number of arguments in C++?

后端 未结 17 1783
-上瘾入骨i
-上瘾入骨i 2020-11-21 23:13

How can I write a function that accepts a variable number of arguments? Is this possible, how?

17条回答
  •  心在旅途
    2020-11-21 23:46

    Apart from varargs or overloading, you could consider to aggregate your arguments in a std::vector or other containers (std::map for example). Something like this:

    template  void f(std::vector const&);
    std::vector my_args;
    my_args.push_back(1);
    my_args.push_back(2);
    f(my_args);
    

    In this way you would gain type safety and the logical meaning of these variadic arguments would be apparent.

    Surely this approach can have performance issues but you should not worry about them unless you are sure that you cannot pay the price. It is a sort of a a "Pythonic" approach to c++ ...

提交回复
热议问题