The challenge of defining generic functions in C can be encountered when the internal functions are themselves generic. This article explores a solution using template template parameters to overcome this hurdle.
Consider the following code snippet illustrating the problem:
<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); } void test() { function<a>(); function<b>(); }</code>
The difficulty arises in determining how to define the function template correctly. To resolve this, we employ a technique known as "template template parameters."
Template template parameters enable us to pass template functions as arguments to other templates. This provides the flexibility to create generic functions that operate on a specific set of template functions.
However, there is a catch: we cannot directly pass template template functions as types. Instead, we must use a workaround with dummy structures.
The following code exemplifies the workaround:
<code class="cpp">template <typename T> struct a { static void foo (T = T ()) { } }; template <typename T> struct b { static void foo (T = T ()) { } }; struct SomeObj {}; struct SomeOtherObj {}; template <template <typename P> class T> void function () { T<SomeObj>::foo (); T<SomeOtherObj>::foo (); } int main () { function<a>(); function<b>(); }</code>
The dummy structures a and b serve as placeholders for the template functions. They provide a method foo that does nothing, primarily to satisfy the syntax requirements.
The function template accepts a template template parameter T, which specifies the type of template function to be executed. It then invokes foo for two different types of objects, SomeObj and SomeOtherObj.
By using this approach, we can define generic functions that operate on a set of template functions in a flexible and type-safe manner.
The above is the detailed content of How can we write a generic function in C that accepts template functions as arguments?. For more information, please follow other related articles on the PHP Chinese website!