Home >Backend Development >C++ >Can Template Functions Be Passed as Template Arguments in C ?

Can Template Functions Be Passed as Template Arguments in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 18:44:02400browse

Can Template Functions Be Passed as Template Arguments in C  ?

Template Function as a Template Argument

In C , generic programming can be achieved through function pointers or templates. While templates ensure inline function calls, they face limitations when dealing with generic functions themselves.

Problem Statement

Consider the following code:

<code class="cpp">void a(int) {
    // do something
}
void b(int) {
    // something else
}

template<void (*param)(int) >
void function() {
    param(123);
    param(456);
}</code>

While this template function simplifies the repetition between function1 and function2, it becomes problematic when a and b are generic themselves:

<code class="cpp">template<typename T>
void a(T t) {
    // do something
}

template<typename T>
void b(T t) {
    // something else
}

template< ...param... > // ???
void function() {
    param<SomeType>(someobj);
    param<AnotherType>(someotherobj);
}</code>

Solution: Template Template Parameters

To define the generic function with generic functions a and b, we need to employ template template parameters. However, passing these functions as types directly is not possible. Therefore, we use a workaround with dummy structures:

<code class="cpp">template<typename T>
struct a {
    static void foo(T = T()) {}
};

template<typename T>
struct b {
    static void foo(T = T()) {}
};

template<template<typename P> class T>
void function() {
    T<SomeObj>::foo();
    T<SomeOtherObj>::foo();
}</code>

By specifying the template template parameter as the dummy structures a and b, we can instantiate the template function and call the generic foo methods within function.

The above is the detailed content of Can Template Functions Be Passed as Template Arguments 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