Home  >  Article  >  Backend Development  >  Can Template Arguments Be Deduced Automatically in C Using `template`?

Can Template Arguments Be Deduced Automatically in C Using `template`?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 02:43:01241browse

Can Template Arguments Be Deduced Automatically in C   Using `template`?

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 could we use 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&amp;) {} // do whatever
};

template <typename T>
foo<T> make_foo(const T&amp; 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!

Statement:
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