Home > Backend Development > C++ > body text

Can Template Deduction Work Based on a Function's Return Type in C ?

Susan Sarandon
Release: 2024-11-06 05:35:02
Original
690 people have browsed it

Can Template Deduction Work Based on a Function's Return Type in C  ?

Template Deduction for Function Based on Its Return Type?

In C , template deduction provides a convenient way to determine template arguments based on the arguments provided to a function call. However, there are certain limitations to template deduction, such as the inability to deduce type arguments based on the return type of a function.

The Issue:

The original question seeks to eliminate the need to explicitly specify type arguments when calling the Allocate() function in the following code:

<code class="cpp">GCPtr<A> ptr1 = GC::Allocate();
GCPtr<B> ptr2 = GC::Allocate();</code>
Copy after login

The Answer:

Unfortunately, template deduction cannot be used to deduce the type arguments based on the return type. Instead, it is the other way around: the return type is determined after the template signature has been matched.

Workaround:

To bypass this limitation, the Allocate() function can be wrapped in a helper function that hides the type argument from the caller:

<code class="cpp">// helper
template <typename T>
void Allocate(GCPtr<T>& p) {
   p = GC::Allocate<T>();
}

int main() {
   GCPtr<A> p = 0;
   Allocate(p);
}</code>
Copy after login

This allows the caller to use the Allocate() function without explicitly specifying the type argument:

<code class="cpp">GCPtr<A> p = 0;
Allocate(p);</code>
Copy after login

Additional Note:

C 11 introduces the auto keyword, which allows the compiler to deduce the type from the initializer. This further simplifies the code:

<code class="cpp">auto p = GC::Allocate<A>(); // p is of type GCPtr<A></code>
Copy after login

The above is the detailed content of Can Template Deduction Work Based on a Function's Return Type in C ?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!