Variable number of arguments in C++?

后端 未结 17 1670
-上瘾入骨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:38

    We could also use an initializer_list if all arguments are const and of the same type

    0 讨论(0)
  • 2020-11-21 23:44

    C-style variadic functions are supported in C++.

    However, most C++ libraries use an alternative idiom e.g. whereas the 'c' printf function takes variable arguments the c++ cout object uses << overloading which addresses type safety and ADTs (perhaps at the cost of implementation simplicity).

    0 讨论(0)
  • 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 <typename T> void f(std::vector<T> const&);
    std::vector<int> 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++ ...

    0 讨论(0)
  • 2020-11-21 23:47

    Using variadic templates, example to reproduce console.log as seen in JavaScript:

    Console console;
    console.log("bunch", "of", "arguments");
    console.warn("or some numbers:", 1, 2, 3);
    console.error("just a prank", "bro");
    

    Filename e.g. js_console.h:

    #include <iostream>
    #include <utility>
    
    class Console {
    protected:
        template <typename T>
        void log_argument(T t) {
            std::cout << t << " ";
        }
    public:
        template <typename... Args>
        void log(Args&&... args) {
            int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
            cout << endl;
        }
    
        template <typename... Args>
        void warn(Args&&... args) {
            cout << "WARNING: ";
            int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
            cout << endl;
        }
    
        template <typename... Args>
        void error(Args&&... args) {
            cout << "ERROR: ";
            int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
            cout << endl;
        }
    };
    
    0 讨论(0)
  • 2020-11-21 23:47

    As others have said, C-style varargs. But you can also do something similar with default arguments.

    0 讨论(0)
提交回复
热议问题