C++11 variable number of arguments, same specific type

前端 未结 6 1815
难免孤独
难免孤独 2020-12-05 01:55

Question is simple, how would I implement a function taking a variable number of arguments (alike the variadic template), however where all arguments have the same type, say

6条回答
  •  攒了一身酷
    2020-12-05 02:18

    A possible solution is to make the parameter type a container that can be initialized by a brace initializer list, such as std::initializer_list or std::vector. For example:

    #include 
    #include 
    
    void func(std::initializer_list a_args)
    {
        for (auto i: a_args) std::cout << i << '\n';
    }
    
    int main()
    {
        func({4, 7});
        func({4, 7, 12, 14});
    }
    

提交回复
热议问题