Anything like the c# params in c++?

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

That is the question.

相关标签:
4条回答
  • 2021-02-18 20:02

    For unmanaged C++ with the same convenient syntax, no.

    But there is support for variable argument lists to functions in C++.

    Basically you declare a function with the last parameter being an ellipsis (...), and within the body of the function use the va_start()/va_arg() calls to parse out the supplied parameter list.

    This mechanism is not type safe, and the caller could pass anything, so you should clearly document the public interface of the function and what you expect to be passed in.

    For managed C++ code, see Reed's comments.

    0 讨论(0)
  • 2021-02-18 20:06

    There is a named parameters library in boost (if I understood correctly what params in C# are). It allows writing functions like this:

    int y = lib::f(_name = "bob", _index = 2);
    

    Can't tell anything about if there is a significant overhead involved.

    0 讨论(0)
  • 2021-02-18 20:11

    Yes. In standard C++, you can use va_arg and the ... syntax. See MSDN for details.

    For C++/CLI, There is a shortcut for this.

    You do this as:

    void TheMethod( String^ firstArgument, ... array<Object^>^ variableArgs );
    

    See this blog post for details.

    0 讨论(0)
  • 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<class T>
    void MyFoo(T arg)
    {
        DoSomething(arg);
    }
    template<class T, class... R>
    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<class T>
    void MyFoo(std::initializer_list<T> 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
    }
    
    0 讨论(0)
提交回复
热议问题