Home > Backend Development > C++ > Can C Deduce Template Types from Function Return Types?

Can C Deduce Template Types from Function Return Types?

Mary-Kate Olsen
Release: 2024-11-06 12:23:02
Original
368 people have browsed it

Can C   Deduce Template Types from Function Return Types?

Template Deduction Based on Function Return Type in C

In C , it can be desirable to utilize template deduction to simplify code that instantiates generic functions based on the data types of the function's arguments. Consider the following example:

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

Instead of specifying the generic type parameters explicitly, the goal is to achieve this deduction using the return type of the GC::Allocate() function. However, C does not allow type deduction based on the return type.

<code class="cpp">class GC
{
public:
    template<typename T>
    static GCPtr<T> Allocate();
};</code>
Copy after login

Despite the return type being generic, the compiler requires the explicit specification of the template type parameters and when instantiating the GC::Allocate() function.

To mitigate this limitation, an auxiliary function can be introduced:

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

Using this function, the original goal can be achieved as follows:

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

Whether this syntax offers any significant advantage over the explicit type specification is subjective.

Note: In C 11, it is possible to omit one of the type declarations using the auto keyword:

<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 C Deduce Template Types from Function Return Types?. 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