Home > Backend Development > C++ > Why Does Template Argument Deduction Fail with `std::map` in a Non-Deducible Context?

Why Does Template Argument Deduction Fail with `std::map` in a Non-Deducible Context?

Linda Hamilton
Release: 2024-12-17 07:33:25
Original
910 people have browsed it

Why Does Template Argument Deduction Fail with `std::map` in a Non-Deducible Context?

Issues with Template Argument Deduction in Non-Deducible Contexts

In this code snippet, we encounter an error when trying to use the test function with a TMap instance:

struct TMap
{
    typedef std::map<T, T> Type;
};

template<typename T>
T test(typename TMap<T>::Type &amp;tmap_) { return 0.0; }

int main()
{
    TMap<double>::Type tmap;
    tmap[1.1] = 5.2;
    double d = test(tmap); // Error
}
Copy after login

The error stems from the compiler's inability to deduce the T template argument from the function's argument tmap. This situation arises because we're in a non-deducible context, where the template argument cannot be inferred from the arguments of the function call.

In template-based programming, there are certain situations where the compiler can automatically deduce the template arguments from the function call arguments. This is known as template argument deduction. However, in this case, the compiler cannot deduce T based on tmap_ because it is an instance of std::map, which is not directly tied to TMap::Type.

If we were to specialize TMap for a specific T type, the compiler would not be able to determine which specialization to apply, given that std::map can be paired with both TMap and TMap.

To resolve this issue, we can explicitly specify the T template argument when calling the test function:

double d = test<double>(tmap);
Copy after login

By specifying double as the template argument, the compiler can correctly deduce the type of tmap_ and conclude that it matches TMap::Type.

The above is the detailed content of Why Does Template Argument Deduction Fail with `std::map` in a Non-Deducible Context?. 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