A function with variable number of arguments with known types, the c++11 way

后端 未结 2 2038
刺人心
刺人心 2020-12-09 09:38

I already know the stdarg.h way to have a function with variable arguments in c++ as discussed here for example. I also know c++11 standard has variadic templat

相关标签:
2条回答
  • 2020-12-09 10:04

    If variable parameters are all of one type, you can change the function signature to take an array of those types instead of using the '...'.

    0 讨论(0)
  • 2020-12-09 10:13

    It is straight forward to write a function with variadic templates, that accept an arbitrary number of arguments. The only difference to the general pattern is, that a concrete type is used as first argument (head) - instead of a template parameter. The following example shows a function foobar, that accepts an arbitrary number of strings.

    // used for end of recursion - and for the empty arguments list
    void foobar() { }
    
    template <typename ...Tail>
    void foobar(const std::string& head, Tail&&... tail)
    {
        // do something with head
        std::cout << head << '\n';
        // call foobar recursively with remaining arguments
        foobar(std::forward<Tail>(tail)...);
    }
    
    foobar("Hello", "World", "...");
    

    Personally, I prefer using std::initializer_list instead of variadic templates. Because variadic templates are more complex and require additional experience. With std::initializer_list, it might look like this:

    void foobar(std::initializer_list<std::string> values)
    {
        for (auto& value : values) {
            // do something with value
            std::cout << value << '\n';
        }
    }
    
    foobar({ "Hello", "World", "...", });
    

    Unfortunately, the additional curly braces are required when using std::initializer_list with regular functions. They are not required for constructors, if the new initializer syntax is used.

    Edit: Rewrote the answer according to the feedback. In particular I have changed the order of the two solutions/examples.

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