The C++17 standard introduces "template deduction guides". I gather they're something to do with the new template argument deduction for constructors introduced in this version of the standard, but I haven't yet seen a simple, FAQ-style explanation of what they are and what they're for.
What are template deduction guides in C++17?
Why (and when) do we need them?
How do I declare them?
Template deduction guides are patterns associated with a template class that tell the compiler how to translate a set of parameter (and their types) into template arguments.
The simplest example is that of
std::vector
and its constructor that takes an iterator pair.The compiler needs to figure out what
vector<T>
'sT
type will be. We know what the answer is;T
should betypename std::iterator_traits<Iterator>::value_type
. But how do we tell the compiler without having to typevector<typename std::iterator_traits<Iterator>::value_type>
?You use a deduction guide:
This tells the compiler that, when you call a
vector
constructor matching that pattern, it will deduce thevector
specialization using the code on the right of->
.You need guides when the deduction of the type from the arguments is not based on the type of one of those arguments. Initializing a
vector
from aninitializer_list
explicitly uses thevector
'sT
, so it doesn't need a guide.The left side doesn't necessarily specify a constructor. The way it works is that, if you use template constructor deduction on a type, it matches the arguments you pass against all deduction guides (actual constructors of the primary template provide implicit guides). If there is a match, it uses that to determine which template arguments to provide to the type.
But once that deduction is done, once the compiler figures out the template parameters for the type, initialization for the object of that type proceeds as if none of that happened. That is, the deduction guide selected does not have to match the constructor selected.
This also means that you can use guides with aggregates and aggregate initialization:
So deduction guides are only used to figure out the type being initialized. The actual process of initialization works exactly as it did before, once that determination has been made.
Here is a use case of deduction guide I used to simplify proxy object construction in a proxy pattern. Hope it may give you some ideas simplest things we can do proxy pattern using modern c++ The deduction guides I used are :