Template Argument Deduction is the ability of templated classes to determine the type of the passed arguments for constructors without explicitly stating the type.
Before C++17, to construct an instance of a templated class we had to explicitly state the types of the argument (or use one of the make_xyz support functions).
std::pair p(2, 4.5);
Here, p is an instance of the class pair and is initialized with values of 2 and 4.5.
Or the other method of achieving this would be:
auto p = std::make_pair(2, 4.5);
Both methods have their drawbacks. Creating “make functions” like std::make_pair is confusing, artificial and inconsistent with how non-template classes are constructed. std::make_pair, std::make_tuple etc are available in the standard library, but for user-defined types it is worse: you have to write your own make_… functions.
In C++17,
This requirement for specifying the types for a templated class constructor has been abolished. This means that we can now write:
auto p = std::pair(2, 4.5);
or
std::pair p(2, 4.5);
which is the logical way you would expect to be able to define p!
Example:
So considering the earlier function mytuple(). Using Template Argument Deduction (and auto for function return type), consider:
Before C++ 17:
auto mytuple()
{
char a = 'a';
int i = 123;
bool b = true;
return std::tuple(a, i, b); // No types needed
}
C++ 17 :
This is a much cleaner way of coding – and in this case we could even wrap it as:
auto mytuple()
{
return std::tuple(‘a’, 123, true); // Auto type deduction from arguments
}
Before C++17, to construct an instance of a templated class we had to explicitly state the types of the argument (or use one of the make_xyz support functions).
std::pair
Here, p is an instance of the class pair and is initialized with values of 2 and 4.5.
Or the other method of achieving this would be:
auto p = std::make_pair(2, 4.5);
Both methods have their drawbacks. Creating “make functions” like std::make_pair is confusing, artificial and inconsistent with how non-template classes are constructed. std::make_pair, std::make_tuple etc are available in the standard library, but for user-defined types it is worse: you have to write your own make_… functions.
In C++17,
This requirement for specifying the types for a templated class constructor has been abolished. This means that we can now write:
auto p = std::pair(2, 4.5);
or
std::pair p(2, 4.5);
which is the logical way you would expect to be able to define p!
Example:
So considering the earlier function mytuple(). Using Template Argument Deduction (and auto for function return type), consider:
Before C++ 17:
auto mytuple()
{
char a = 'a';
int i = 123;
bool b = true;
return std::tuple(a, i, b); // No types needed
}
C++ 17 :
This is a much cleaner way of coding – and in this case we could even wrap it as:
auto mytuple()
{
return std::tuple(‘a’, 123, true); // Auto type deduction from arguments
}
Comments
Post a Comment