Search code examples
c#c++parameters

Anything like the c# params in c++?


That is the question.

Background: C# Params

In C#, you can declare the last parameter in a method / function as 'params', which must be a single-dimension array, e.g.:

public void SomeMethod(int fixedParam, params string[] variableParams)
{
   if (variableParams != null)
   {
        foreach(var item in variableParams)
        {
            Console.WriteLine(item);
        }
   }
}

This then essentially allows syntactic sugar at the call site to implicitly build an array of zero or more elements:

SomeMethod(1234); // << Zero variableParams
SomeMethod(1234, "Foo", "Bar", "Baz"); // << 3 variableParams

It is however still permissable to bypass the sugar and pass an array explicitly:

SomeMethod(1234, new []{"Foo", "Bar", "Baz"});

Solution

  • 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.