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:
template
struct a {
static void foo(T = T()) {}
};
template
struct b {
static void foo(T = T()) {}
};
struct SomeObj {};
struct SomeOtherObj {};
template class T>
void function() {
T::foo();
T::foo();
}
int main() {
function();
function();
}
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3