Anything like the c# params in c++?

后端 未结 4 1250
后悔当初
后悔当初 2021-02-18 19:26

That is the question.

4条回答
  •  温柔的废话
    2021-02-18 20:25

    Nowadays, with modern C++, you can use modern type-safe practices for variadic functions.

    Use either variadic templates or std::initializer_list if all your arguments have the same type

    With variadic template, you use recursion to go through a variadic parameter list. Variadic template example:

    template
    void MyFoo(T arg)
    {
        DoSomething(arg);
    }
    template
    void MyFoo(T arg, R... rest)
    {
        DoSomething(arg);
        // If "rest" only has one argument, it will call the above function
        // Otherwise, it will call this function again, with the first argument
        // from "rest" becoming "arg"
        MyFoo(rest...); 
    }
    
    int main()
    {
        MyFoo(2, 5.f, 'a');
    }
    

    This guarantees that if DoSomething, or any other code you run before the recursive call to MyFoo, has an overload for the type of each argument you pass to the function MyFoo, that exact overload will get called.

    With std::initializer_list, you use a simple foreach loop to go through the arguments

    template
    void MyFoo(std::initializer_list args)
    {
        for(auto&& arg : args)
        {
            DoSomething(arg);
        }
    }
    int main()
    {
        MyFoo({2, 4, 5, 8, 1, 0}); // All the arguments have to have the same type
    }
    

提交回复
热议问题