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>
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>
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>
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>
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!