Q:
While using C 11 with g 4.7, an attempt to compile code using the std::make_pair function with explicitly specified template parameters fails. Understanding the cause of this error is the objective.
A:
Incorrect Usage for make_pair
std::make_pair is intended for automatic template argument deduction. Explicitly specifying template parameters prevents this deduction, leading to a mismatch between the actual and expected argument types. The function takes arguments of type T&& and U&&, where T and U are template type parameters, effectively resembling:
template<typename T, typename U> make_pair(T&& argT, U&& argU);
Argument Type Discrepancy
When specifying template parameters explicitly, no argument deduction occurs. Instead, the specified types are used directly in the function template, resulting in:
make_pair(std::string&& argT, int&& argU);
In this case, both parameter types are rvalue references, which can only bind to rvalues. However, one of the arguments, s, is an lvalue (an existing object), making it incompatible with the expected rvalue reference type. Thus, the function template cannot match the supplied arguments, leading to the compilation error.
Correct Usage for make_pair
To resolve this issue, remove the explicit template parameter specification and allow automatic argument deduction. In this scenario, the compiler can deduce T to be std::string, as s is an lvalue of type std::string, resulting in std::string& as the final argument type. Similarly, U is deduced to be int, with the argument 7 being an rvalue of type int, resulting in int&&. These argument types correctly match the function template, allowing for successful compilation.
General Guideline for Templates
For templates, it's generally advised to let the compiler perform template argument deduction whenever possible. Explicitly specifying template parameters should only be done when absolutely necessary.
The above is the detailed content of Why Does Explicitly Specifying Template Parameters in C 11's `std::make_pair` Fail to Compile?. For more information, please follow other related articles on the PHP Chinese website!