Home > Article > Backend Development > 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>
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>
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>
Using this function, the original goal can be achieved as follows:
<code class="cpp">GCPtr<A> p; Allocate(p);</code>
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>
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!