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

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

Susan Sarandon
Release: 2024-11-05 02:43:01
Original
321 people have browsed it

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>
Copy after login

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>
Copy after login

Now, instead of writing:

<code class="cpp">foo<int>(5);</code>
Copy after login

We can simply write:

<code class="cpp">make_foo(5);</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template