Home >Backend Development >C++ >Why Does `std::make_pair` Fail with Explicit Template Arguments in C 11?
In the realm of C , the std::make_pair function has risen to prominence as a convenient tool for creating pairs. However, a peculiar issue arises when attempting to employ this function with explicitly specified template parameters in C 11. This article delves into the enigmatic behavior behind this situation.
Consider the following code snippet that attempts to create a pair of a string and an integer with explicit template arguments:
std::pair<std::string, int>& b = std::make_pair<std::string, int>(s, 7);
Instead of the expected compilation success, a cryptic error message emerges:
error: no matching function for call to 'make_pair(std::string&, int)'
The source of this error lies in the incorrect usage of std::make_pair. The function was designed to infer the template parameters based on the provided arguments. Explicitly stating these parameters hinders this inference process.
The C 11 implementation of std::make_pair takes two parameters of type T&& and U&&, where T and U are template type parameters. When explicitly specifying the template arguments, as seen in the problematic code, no argument deduction occurs. Instead, the specified types are directly substituted into the template declaration, resulting in the following:
make_pair(std::string&& argT, int&& argU);
Note that both parameters in the explicitly specified template are rvalue references (&&), which can only bind to rvalue expressions. In the provided code, s is an lvalue (not a temporary and not being moved). Consequently, the function template fails to match the arguments, leading to the compilation error.
When omitting the explicit template arguments, argument deduction takes place. Due to the special nature of rvalue reference parameters in templates (reference collapsing), an rvalue reference parameter of type A&&, where A is a template type parameter, can bind to any type of A. Whether A is an lvalue, rvalue, qualified or not, an A&& can bind to it.
In the example code, s is an lvalue of type std::string and 7 is an rvalue of type int. The compiler deduces T to be std::string& and U to be int, allowing s and 7 to bind successfully to the inferred parameter types.
To avoid such errors, adhere to the following principle: If a template argument can be deduced from the function arguments, allow the compiler to perform the deduction. Explicitly providing arguments is often unnecessary and can lead to unexpected results. By harnessing the power of argument deduction, programmers can simplify their code and enhance its readability while maintaining its correctness.
The above is the detailed content of Why Does `std::make_pair` Fail with Explicit Template Arguments in C 11?. For more information, please follow other related articles on the PHP Chinese website!