Home >Backend Development >C++ >How does the ellipsis (...) token work in C 11 variadic templates?

How does the ellipsis (...) token work in C 11 variadic templates?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 01:03:28782browse

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:

  • Unpacking (Right Side): When used on the right-hand side of an expression, ... unpacks a template parameter pack. The unpacked patterns, separated by commas, replace the ellipsis in the actual function call.
  • Packing (Left Side): When placed on the left-hand side, ... packs arguments into a template parameter pack. The packed arguments are available within the function as a single entity.

Example of Unpacking

Consider the following variadic template function:

<code class="cpp">template< class T, class... Args >
unique_ptr<T> make_unique( Args&amp;&amp;... 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:

  • Creating arrays with variadic initializers
  • Defining classes that inherit from multiple base classes (via a public Mixins... syntax)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn