Home > Backend Development > C++ > Is There a `template` Equivalent in C ?

Is There a `template` Equivalent in C ?

Mary-Kate Olsen
Release: 2024-11-06 05:26:02
Original
371 people have browsed it

Is There a `template` Equivalent in C  ?

Can You Mimic Template?

C 's template metaprogramming capabilities allow developers to create powerful and efficient code. However, in certain scenarios, passing arguments to templates can be cumbersome. Consider the following code:

<code class="cpp">struct Foo {
  template<class T, T X>
  void bar() {
    // do something with X, compile-time passed
  }
};

struct Baz {
  void bang() {}
};

int main() {
  Foo f;
  f.bar<int, 5>();
  f.bar<decltype(&Baz::bang), &Baz::bang>();
}</code>
Copy after login

In this example, we need to explicitly specify the types and pass the actual values as arguments to the template bar.

Is it possible to simplify this syntax? Could we express it as follows:

<code class="cpp">struct Foo {
  template<auto X>
  void bar() {
    // do something with X, compile-time passed
  }
};

struct Baz {
  void bang() {}
};

int main() {
  Foo f;
  f.bar<5>();
  f.bar<&Baz::bang>();
}</code>
Copy after login

The Answer:

Unfortunately, C does not provide a direct way to achieve this syntax. The closest alternative is 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

Another Alternative: Generators

If you're primarily seeking a way to avoid explicitly specifying types, a generator function can be a viable solution:

<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

Instead of writing:

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

You can use:

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

This allows the argument type to be deduced, simplifying the code. Note that this approach doesn't directly emulate template syntax, but it provides a convenient alternative for passing arguments to templates.

The above is the detailed content of Is There a `template` Equivalent in C ?. 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