Home >Backend Development >C++ >How does the ellipsis (...) token work in C 11 variadic templates?
Variadic Templates and the Ellipsis ("...") Token
In C 11, variadic templates allow for a flexible number of template parameters. When defining a variadic template, the ellipsis (...) token plays a crucial role.
Unpacking vs. Packing
The position of the ellipsis determines its function:
Example of Unpacking
Consider the following variadic template function:
<code class="cpp">template< class T, class... Args > unique_ptr<T> make_unique( Args&&... args ) { return unique_ptr<T>(new T(std::forward<Args>(args)...)); }</code>
When invoking make_unique with multiple arguments, the ellipsis (in std::forward(Args>(args)...) allows the function to accept a variable number of arguments. The ellipsis unpacks the Args parameter pack, resulting in the following expanded expression:
<code class="cpp">std::forward<Arg0>(arg0), std::forward<Arg1>(arg1), ...</code>
Ellipsis Placement in Template and Function Arguments
In the template argument list, the ellipsis is placed in the middle to indicate that the parameter pack is continued in the function parameter list. This is because there may be additional template parameters (e.g., non-variadic parameters) following the variadic parameter pack.
In the function implementation, the ellipsis is placed at the end of the expression to mark the end of the unpacked arguments. It ensures that any remaining arguments are passed without being packed into a single entity.
Additional Applications
The ellipsis can also be used in other contexts, such as:
The above is the detailed content of How does the ellipsis (...) token work in C 11 variadic templates?. For more information, please follow other related articles on the PHP Chinese website!