Question

That is the question.

Was it helpful?

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.

OTHER TIPS

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.

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
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top