Automating Template Argument Deduction with template
Question:
Can template arguments be passed during compile-time without explicitly specifying their types? For instance, instead of template
Answer:
The mentioned approach is not possible in C . The closest alternative involves using macros:
<code class="cpp">#define AUTO_ARG(x) decltype(x), x f.bar<AUTO_ARG(5)>(); f.bar<AUTO_ARG(&Baz::bang)>();</code>
An alternative approach is to use a generator function that deduces the template argument:
<code class="cpp">template <typename T> struct foo { foo(const T&) {} // do whatever }; template <typename T> foo<T> make_foo(const T& x) { return foo<T>(x); }</code>
Now, instead of writing:
<code class="cpp">foo<int>(5);</code>
We can simply write:
<code class="cpp">make_foo(5);</code>
This method automates template argument deduction, providing a more convenient way to pass arguments.
The above is the detailed content of Can Template Arguments Be Deduced Automatically in C Using `template`?. For more information, please follow other related articles on the PHP Chinese website!