Home > Backend Development > C++ > Why Does Explicitly Specifying Template Parameters in C 11's `make_pair` Fail to Compile?

Why Does Explicitly Specifying Template Parameters in C 11's `make_pair` Fail to Compile?

Mary-Kate Olsen
Release: 2024-12-21 11:43:17
Original
151 people have browsed it

Why Does Explicitly Specifying Template Parameters in C  11's `make_pair` Fail to Compile?

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template