I can't understand what does the following piece of C++ code does:
template<typename... Ts>
void print(Ts &&... ts)
{
ns::logger{ (print(std::forward<Ts>(ts)), ns::s{})... };
}
I see that there's perfect forwarding with variadic arguments, but what is happening in the line below precisely?
My guess is that an object of type ns::logger
is being uniform initialized with a series of values but I'm not sure which ones.. is that ...
a folding expression?
Perfect forwarding allows a template function that accepts a set of arguments to forward these arguments to another function whilst retaining the lvalue or rvalue nature of the original function arguments.
std::forward helps to implement perfect forwarding. This mechanism implies that objects passed to the function as lvalue expressions should be copied, and objects passed to the function as rvalue expressions should be moved. If you assign an rvalue reference to some ref variable, then ref is a named entity.
ns::logger
is being initialized with a list of expressions (print(std::forward<Ts>(ts)), ns::s{})
, one for each element in ts
.
Each expression, in turn, uses a comma operator. It calls print(std::forward<Ts>(ts))
and discards its result (if any). Then it constructs ns::s{}
, and that object becomes the result of the comma operator.
The net result is roughly equivalent to this pseudocode:
print(std::forward<Ts_1>(ts_1));
print(std::forward<Ts_2>(ts_2));
...
print(std::forward<Ts_N>(ts_N));
ns::logger{ns::s{}, ns::s{}, ... /* repeated N times */};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With