Home > Article > Backend Development > Can Automatic Type Inference Emulate Template Inheritance in C ?
Emulating Template Inheritance with Automatic Type Inference
The ability to specify template arguments automatically using auto would provide a convenient shortcut in situations where explicitly typing out full types can be tedious or complex. However, it's important to note that C does not currently support the direct emulation of template
Using Macros for Convenient Argument Passing
As a workaround, macros can be utilized to simulate automatic type inference. Consider the following example:
<code class="cpp">#define AUTO_ARG(x) decltype(x), x Foo f; f.bar<AUTO_ARG(5)>(); // Equivalent to f.bar<int, 5>() f.bar<AUTO_ARG(&Baz::bang)>(); // Equivalent to f.bar<decltype(&Baz::bang), &Baz::bang>()</code>
While this approach can simplify the calling syntax, it introduces potential pitfalls and requires explicit macro calls.
Leveraging a Template Generator for Automatic Deduction
An alternative solution involves creating a template generator function:
<code class="cpp">template <typename T> struct foo { foo(const T&) {} // Perform specific actions }; template <typename T> foo<T> make_foo(const T& x) { return foo<T>(x); }</code>
With this generator, instead of explicitly specifying the template argument type:
<code class="cpp">foo<int>(5);</code>
One can use the deduction capabilities of the generator function:
<code class="cpp">make_foo(5); // Deduces and creates foo<int>(5)</code>
The above is the detailed content of Can Automatic Type Inference Emulate Template Inheritance in C ?. For more information, please follow other related articles on the PHP Chinese website!