Template Argument Deduction in C++17

Template Argument deduction is the ability of the template class to automatically deduce the type without specifying it. In order to instantiate a class template, every template argument must be known, but not every template argument has to be specified.

Any template without argument type mentioned

	std::pair p(23, 'c'); //Pair is deduced as integer and char without mentioning the types
	std::tuple t(15, 16.34, "test");

Pair is deduced as integer and char without mentioning the types. The tuple types are deduced as integer, float and string this is the same as

auto t = make_tuple(15, 16.34, "test" );

The deduction happens only when the template argument list is not provided. If there is a list provided then the deduction does not happen.

For example:

std::tuple<>(15, 16.34, "test" ); //This is an ERROR!!!!
std::tuple<int>(1,2,3); //This is an ERROR

//Copy deduction is preferred over the wrapping by defualt
std::tuple t1{1};   //std::tuple<int>
std::tuple t2{t1};  //std::tuple<int>, not std::tuple<std::tuple<int>>
std::vector v1{1, 2};   // std::vector<int>
std::vector v2{v1};     // std::vector<int>, not std::vector<std::vector<int>> (P0702R1)
std::vector v3{v1, v2}; // std::vector<std::vector<int>> 

Outside the special case for copying vs. wrapping, the strong preference for initializer-list constructors in list-initialization remains intact.

std::vector v1{1, 2}; // std::vector<int>
 
std::vector v2(v1.begin(), v1.end());  // std::vector<int>
std::vector v3{v1.begin(), v1.end()};  // std::vector<std::vector<int>::iterator>

Prev: Direct Initialization Next: Nested Namespace and __has_include

References:

C++ Class Template Deduction link.

2 thoughts on “Template Argument Deduction in C++17

Comments are closed.