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

前端 未结 6 1834
难免孤独
难免孤独 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:23

    Because I don't think I saw this solution, you could write a specific function for every type (in your case, just int) then a forwarding function taking variadic argument types.

    Write each specific case:

    then for each specific case:

    // only int in your case
    void func(int i){
        std::cout << "int i = " << i << std::endl;
    }
    

    Then your forwarding function like this:

    template
    void func(Arg0 &&arg0, Arg1 &&arg1, Args &&... args){
        func(std::forward(arg0));
        func(std::forward(arg1), std::forward(args)...);
    }
    

    This is good because it is expandable for when you want to accept maybe another type too.

    Used like this:

    int main(){
        func(1, 2, 3, 4); // works fine
        func(1.0f, 2.0f, 3.0f, 4.0f); // compile error, no func(float)
    }
    

提交回复
热议问题