Variable number of arguments in C++?

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

    A C++17 solution: full type safety + nice calling syntax

    Since the introduction of variadic templates in C++11 and fold expressions in C++17, it is possible to define a template-function which, at the caller site, is callable as if it was a varidic function but with the advantages to:

    • be strongly type safe;
    • work without the run-time information of the number of arguments, or without the usage of a "stop" argument.

    Here is an example for mixed argument types

    template
    void print(Args... args)
    {
        (std::cout << ... << args) << "\n";
    }
    print(1, ':', " Hello", ',', " ", "World!");
    

    And another with enforced type match for all arguments:

    #include  // enable_if, conjuction
    
    template
    using are_same = std::conjunction...>;
    
    template::value, void>>
    void print_same_type(Head head, Tail... tail)
    {
        std::cout << head;
        (std::cout << ... << tail) << "\n";
    }
    print_same_type("2: ", "Hello, ", "World!");   // OK
    print_same_type(3, ": ", "Hello, ", "World!"); // no matching function for call to 'print_same_type(int, const char [3], const char [8], const char [7])'
                                                   // print_same_type(3, ": ", "Hello, ", "World!");
                                                                                                  ^
    

    More information:

    1. Variadic templates, also known as parameter pack Parameter pack(since C++11) - cppreference.com.
    2. Fold expressions fold expression(since C++17) - cppreference.com.
    3. See a full program demonstration on coliru.

提交回复
热议问题