Home > Article > Backend Development > How Can Template Functions Be Used as Template Arguments in C ?
In C , how can a template function be utilized as a template argument to achieve code reuse while maintaining generic functionality, particularly when the involved functions themselves are also templates?
To address this problem, employ a template template parameter. The primary concept is that template parameters cannot directly include template template functions due to the need for prior instantiation. A workaround involves using dummy structures to encapsulate the template function:
<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>
In this example, the structures a and b implement template functions for the foo method. The function template takes a template template parameter, allowing us to pass the a and b templates as arguments. Within function, specific instances of the dummy structures are created, enabling the invocation of foo with different parameter types.
The above is the detailed content of How Can Template Functions Be Used as Template Arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!