C 17 Template Deduction Guides: A Simple Explanation
What are Template Deduction Guides?
Template deduction guides are a feature introduced in C 17 that assist the compiler in inferring template arguments for constructors. They provide a way to specify how constructor arguments and their types map to template parameters.
Why (and When) Do We Need Them?
Template deduction guides are necessary when the deduction of template arguments from constructor arguments cannot be done directly from the argument types. For example, initializing a vector from an iterator pair requires knowledge of the underlying value type of the iterator.
How to Declare Them?
Template deduction guides are declared using the following syntax:
template <template-argument-list> class-template id (function-parameter-list) -> deduced-type;
Here, template-argument-list indicates the template arguments that are being deduced, function-parameter-list represents the constructor arguments, and deduced-type is the resulting deduced template type.
Example:
Consider the std::vector constructor that takes an iterator pair:
template <typename Iterator> void func(Iterator first, Iterator last) { vector v(first, last); }
To deduce the type T of the vector, we need to use a template deduction guide:
template <typename Iterator> vector(Iterator b, Iterator e) -> vector<typename std::iterator_traits<Iterator>::value_type>;
This guide instructs the compiler to deduce T as the value_type of the std::iterator_traits for the given iterator type.
Aggregate Initialization with Deduction Guides:
Template deduction guides can also be used with aggregate initialization:
template <typename T> struct Thingy { T t; }; Thingy(const char *) -> Thingy<std::string>; Thingy thing{"A String"}; //thing.t is a `std::string`.
In this example, the deduction guide enables the initialization of Thingy with a const char* while deducing T as std::string.
Note: Deduction guides are only used to infer template arguments. The actual initialization process follows the same rules as before, regardless of the chosen deduction guide.
The above is the detailed content of How Do C 17 Template Deduction Guides Simplify Template Argument Inference?. For more information, please follow other related articles on the PHP Chinese website!