Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't understand a piece of C++ code with perfect forwarding and ellipses

Tags:

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?

like image 560
Dean Avatar asked Aug 27 '17 18:08

Dean


People also ask

What is perfect forwarding?

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.

What is the point of std :: forward?

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.


1 Answers

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 */};
like image 123
Igor Tandetnik Avatar answered Oct 11 '22 12:10

Igor Tandetnik