C 11 make_pair With Explicit Template Parameters Fails to Compile
In C 11, the make_pair function is designed to facilitate the creation of pairs with specified data types. However, specifying the template parameters explicitly in the function call can lead to compilation errors.
The make_pair function follows a template syntax:
template<typename T, typename U> make_pair(T&& argT, U&& argU);
This syntax indicates that make_pair accepts two rvalue references, argT and argU, and deduces the template type parameters T and U from the specified arguments.
When explicitly providing the template arguments, as in:
std::make_pair<std::string, int>(s, 7);
rvalue reference parameters are expected. However, the passed lvalue argument s does not satisfy this requirement. Therefore, the compiler fails to establish a match between the argument types and the rvalue reference parameter types.
In contrast, when the template arguments are omitted, the compiler performs template argument deduction, which successfully binds s to T (std::string&) and 7 to U (int&&). This process is facilitated by the unique behavior of rvalue references within template parameters, where they can bind to any type of the same template parameter, regardless of lvalue or rvalue status.
To resolve the error, simply omit the explicit template parameter specification.
The above is the detailed content of Why Does Explicitly Specifying Template Parameters in C 11's `make_pair` Fail to Compile?. For more information, please follow other related articles on the PHP Chinese website!