Search code examples
c++c++11lambdaautovariadic-functions

Function parameter pack


I recently saw the following code excerpt in the Working Draft, Standard for Programming Language C++ (dated 2016-05-30, page 96).

auto vglambda = [](auto printer) {
    return [=](auto&& ... ts) { // OK: ts is a function parameter pack
        printer(std::forward<decltype(ts)>(ts)...);
        return [=]() {
            printer(ts ...);
        };
    };
};

I cannot make sense of the ellipses here. They are not old ellipses in the 'C' sense since they are being expanded. They are not parameter pack in the sense of the "template parameter pack" since there is no template to be seen. In the comment it refers to these as a function parameter pack.

I investigated to see if I could define a regular function with a parameter pack.

void f(auto&& ...ts) {} // error

which did not compile but

auto k = [](auto&& ...ts){};

compiles fine and I can call it as expected

k(1, 2, 3);

It appears to me that this is just a template parameter pack in disguise as lambdas are functors in disguise. Thus, it is only possible with lambda expressions.

I would appreciate clarifications and/or elucidations.


Solution

  • auto lambdas where added in C++14.

    This permits you to create lambdas with a template operator().

    You do this with the

    [](auto x){}
    [](auto...xs){}
    [](auto& xs){}
    [](auto&...xs){}
    [](auto&& xs){}
    [](auto&&...xs){}
    [](auto const& xs){}
    [](auto const&...xs){}
    

    syntaxes. Note that non-template arguments can be added (the above is not exhastive). These correspond to auto being mapped to an implicit template type argument.

    There is some talk of expanding this to normal functions in the concepts proposal, which was deferred in C++14, C++17 and is now a TS possible in C++20.