Home > Backend Development > C++ > Why Does `std::make_pair` Fail with Explicit Template Parameters in C 11?

Why Does `std::make_pair` Fail with Explicit Template Parameters in C 11?

DDD
Release: 2024-12-16 16:58:17
Original
877 people have browsed it

Why Does `std::make_pair` Fail with Explicit Template Parameters in C  11?

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);
Copy after login

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)’
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template