23

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"});
2
  • 3
    Can you please tell us C++ programmers what you man with "C# params" ? Jul 20, 2009 at 21:20
  • 1
    @JohannesSchaub-litb it's the params keyword
    – jxramos
    Apr 28, 2016 at 2:30

5 Answers 5

29

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.

2
  • Nice to know about that ... wasn't aware C++ had this extension for managed code.
    – LBushkin
    Jul 20, 2009 at 20:12
  • @LBushkin: Updated to the better syntax. Jul 20, 2009 at 20:13
17

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.

9

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
}
1
  • It might be noteworthy you can also combine static_assert and variadic templates to make you own flexible initializer list. F.ex. you can combine std::is_base_of with a static_assert on T in your example to ensure that all types are derived of a certain base class.
    – atlaste
    Sep 11, 2015 at 12:42
0

Yes! C++11 and above allows function templates to take a type-safe variable number of arguments, creating what's known as a "parameter pack". You can unpack that into, e.g., a std::array and get something a lot like you are looking for:

struct S {
    template <typename... Args>
    void SomeMethod(int someParam, Args&&... args) const {
        //^ The "&&" here is a "forwarding reference" because Args is a template.
        // Next line isn't required but arguably helps with error messages:
        static_assert((std::is_convertible_v<Args, std::string_view> && ...), "All args in the pack must convert to string_view.");
        // Convert args... to a std::array<std::string_view, N>:
        const auto variableParams = std::array<std::string_view, sizeof...(args)>{std::forward<Args>(args)...};
        if (not variableParams.empty()) { //< Not needed because it's a nop to iterate over an empty array:
            for (const auto& item : variableParams) {
                fmt::print("{}\n", item);
            }
        }
    }
};

int main() {
    S s;
    s.SomeMethod(42, "foo", "bar", "baz");
}

output:

foo
bar
baz

https://godbolt.org/z/PbPb7qTv9

In C++20, you can use concepts to get a better error message and to be more concise:

    void SomeMethod(int someParam, 
                    std::convertible_to<std::string_view> auto&&... args) const {

Happy case: https://godbolt.org/z/aTG74Wx7j Error case: https://godbolt.org/z/jToxYMThs

-1

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.

1
  • 3
    C# params isn't named params - it's variable length argument lists. Jul 20, 2009 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.