Function execution for each packed parameter in a variational pattern

I noticed the following line in the open source FeatherKit project :

int _[] = { (SubscribeToType<MessageTypes>( bus, receiver, desubscribers, unsubscribe ), 0)... };

      

In the following context:

template<class... MessageTypes>
void Subscribe( MessageBus& bus, MessageReceiver<MessageTypes...>& receiver, bool unsubscribe ) {
    std::vector<std::function<void()>> desubscribers;
    int _[] = { (SubscribeToType<MessageTypes>( bus, receiver, desubscribers, unsubscribe ), 0)... };
    (void) _;
    receiver.desubscribers = desubscribers;
}

      

It explicitly executes the SubscribeToType function for each parameter in the variation pattern.

My question is twofold:

  • How does the line actually work? Why does parameter unpacking allow this function to execute for every parameter in the variational pattern?

  • I'm pretty sure this line can be replaced with a lambda. How could you replace a string with a lambda expression?

I contacted the original FeatherKit author, but he was unable to answer my question at the time.

+3


source to share


1 answer


  • How does the line actually work? Why does parameter unpacking allow this function to execute for every parameter in the variational pattern?

A parameter pack extension is some kind of pattern that includes a parameter pack followed by ...

So expr(T)...

- this is a package extension with expr(T)

as its template, and it expands to expr(T0), expr(T1), expr(T2), ..., expr(TN)

for each Ti

in the options package.

A package extension can only be used in certain contexts, such as argument lists or initializer lists, so in this case the results of each subexpression are used to form the initialization list for the array int _[]

. The array is not used and only exists so that its initializer can be used as a context for extending the package. Each subexpression is of the form (SubscribeToType<Ti>(blah, blah), 0)

, which means that the result of the function call is discarded and the expression is set to 0. This is the kluge bit to allow the package extension to create an init-bound list containing N integers, because this is needed to initialize the array.



  1. I'm pretty sure this line can be replaced with a lambda. How could you replace a string with a lambda expression?

Why do you need?

Possibly, but you will need a very similar package extension in lambda so it won't simplify anything.

+1


source







All Articles