C 11 make_pair Fails with Explicit Template Parameters
Problem:
When using g 4.7 with -std=c 11 enabled, the following code fails to compile:
std::pair<std::string, int>& b = std::make_pair<std::string, int>(s, 7);
Despite the existence of the make_pair function, the compiler errors out.
Explanation:
std::make_pair is intended to be used without explicitly specifying template parameters. In C 11, it takes two rvalue reference arguments, T&& and U&&, where T and U are template type parameters. However, explicitly specifying the template arguments leads to a mismatch between the expected rvalue references and the provided lvalue argument (s in the example code).
Consequently, the compiler reports:
error: no matching function for call to ‘make_pair(std::string&, int)’
When template arguments are not explicitly provided, template argument deduction occurs. This allows an rvalue reference template parameter to bind to an lvalue when it appears as a function argument. In the case of std::make_pair without template arguments, the compiler deduces T to be std::string& and U to be int and successfully binds s and 7 to the function arguments.
Solution:
The recommended usage of std::make_pair is to omit the template arguments, relying on template argument deduction. By following this rule, the compiler will handle the argument matching correctly and avoid compilation errors.
The above is the detailed content of Why Does `std::make_pair` Fail with Explicit Template Parameters in C 11?. For more information, please follow other related articles on the PHP Chinese website!