Syntax Rules for the "..." Token in Variadic Templates
In C , variadic templates enable the construction of templates that accept a variable number of arguments. The "..." token plays a crucial role in this context, serving as either an argument pack or a parameter unpacker.
Syntax Rules for Ellipsis Placement
The placement of the "..." token determines its function:
Example: Variadic Template with "..."
Consider the following variadic template:
template
unique_ptr make_unique( Args&&... args )
{
return unique_ptr(new T(std::forward(args)...));
}
In this example, "..." serves as an argument pack, while the "..." in the function implementation unpacks the arguments into the args variable.
Reason for Different Ellipsis Placement
The difference in ellipsis placement between the template argument list and the parameter list is due to the distinction between argument packing and parameter unpacking. In the template argument list, "..." signifies that the parameters should be packed into a single parameter pack, while in the parameter list, "..." indicates that the arguments should be unpacked into individual parameters.
Unpacking Patterns
When "..." appears on the right side of an expression as an unpacker, it follows a specific pattern:
Advanced Usage: Initializing Arrays
Ellipsis can also be used to initialize arrays:
struct data_info
{
boost::any data;
std::size_t type_size;
};
std::vector v{{args, sizeof(T)}...}; //pattern = {args, sizeof(T)}
This initializes the vector v with values where each element is a struct containing an args and a sizeof(T) pair.
In conclusion, the "..." token in the context of variadic templates serves as both an argument pack and a parameter unpacker, following specific syntax rules for placement and unpacking patterns. Its flexible usage allows for powerful template constructs and customization.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3