Template argument deduction is used when selecting user-defined conversion function template arguments. A is the type that is required as the result of the conversion. P is the return type of the conversion function template.
Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. In C++, the auto keyword(added in C++ 11) is used for automatic type deduction.
A template is a C++ programming feature that permits function and class operations with generic types, which allows functionality with different data types without rewriting entire code blocks for each type.
Class Template Argument Deduction (CTAD) is a C++17 Core Language feature that reduces code verbosity. C++17's Standard Library also supports CTAD, so after upgrading your toolset, you can take advantage of this new feature when using STL types like std::pair and std::vector.
When writing generic functions for "iterator" ranges I usually do:
template <typename Iter> auto func(Iter &first, Iter &last)
{
using IterType = typename std::decay<decltype(*first)>::type;
...
}
Another way seems to be:
template <typename Iter> auto func(Iter &first, Iter &last)
{
using IterType = typename std::iterator_traits<Iter>::value_type;
...
}
And yet a third:
template <typename Iter> auto func(Iter &first, Iter &last)
{
using IterType = typename Iter::value_type;
...
}
Without applying iterator_traits
.
In theory, my functions should only receive iterators as first
and last
and the second form would ideally (imho) the most idiomatic way to get the type. But is using typename std::decay<decltype(*first)>::type
the most generic idiom in order to not impose restrictions to Iter
like having a value_type
defined?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With