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

Is There a `template` Equivalent in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 05:26:02254browse

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>

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>

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>

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>

Instead of writing:

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

You can use:

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

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!

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