Is it possible to include more than one function in the same template instead of rewriting the template twice? Like if you were writing:
template <typename T>
void A() {
//...
}
template <typename T>
void B() {
//...
}
Those are not the same function, but they share a similar template (using the generic type T
). Is there a way to initialize the template only once?
Can there be more than one argument to templates? Yes, like normal parameters, we can pass more than one data type as arguments to templates.
You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.
Function Templates with Multiple ParametersYou can also use multiple parameters in your function template. The above syntax will accept any number of arguments of different types. Above, we used two generic types such as A and B in the template function.
Multiple parameters can be used in both class and function template. Template functions can also be overloaded. We can also use nontype arguments such as built-in or derived data types as template arguments.
Grouping them inside a class template would achieve that.
template <class T>
struct Functions {
static void A() { /*...*/ }
static void B() { /*...*/ }
};
However, you lose the ability to deduce T
from the functions' arguments, and the calling syntax is longer :
Functions<double>::A();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With