If several functions which use the same template are needed, is there a way to declare and implement them without declaring the template each time?
template <typename T>
T mymax (T a, T b);
template <typename T>
T mymin (T a, T b);
template <typename T>
T myfoo (T a, T b);
/********************************************/
template <typename T>
T mymax (T a, T b) {
return (a > b ? a : b);
}
template <typename T>
T mymin (T a, T b) {
return (a < b ? a : b);
}
template <typename T>
T myfoo (T a, T b) {
return max(a,b)+min(a,b);
}
Is there a way to write the line template <typename T>
just one time for a block of code? Something that will look like:
template <typename T> {
T mymax (T a, T b);
T mymin (T a, T b);
T myfoo (T a, T b);
}
(this code isn't legal syntax and doesn't compile)
The only way to achieve something like this is to misuse a struct and static functions. Unfortunately, you'll need to explicitly mention the template type.
#include <iostream>
template<typename T>
struct my
{
static T max(T a, T b) { return (a > b ? a : b); }
static T min(T a, T b) { return (a < b ? a : b); }
static T foo(T a, T b) { return max(a, b) + min(a, b); }
};
Live Demo. Pick a better class name.
I can't think any "better" solution. Just write the template<typename T>
. You'll get used to it. It serves a purpose, and it really isn't as ugly as you think.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments