G
Gina Yarmel
I am writing an application that has two classes that I would like to
treat like vectors (in the mathematical sense); I'd like * and +
operations for scalar multiplication. I also need the std::vector
interface for its dynamic allocation. So, I inherit from std::vector,
and I want to write a function
template<typename S, typename T>
T operator*(const S & op1, const T & op2) {
T ans(op2);
for(typename T::iterator i = ans.begin(); i != ans.end(); ++i) {
i = op1 * *i;
}
return ans;
}
My problem is that this grabs calls for T=<some enum type>. I've
thought of two ways I could prevent this disaster, none of which are
legal C++.
1. I want some sort of bounded polymorphism where T must be a subtype
of vector<S>.
2. I want some sort of "thistype" identifier, so that I can write the
above definition, with "T" replaced by "thistype", and the definition
placed in some "myvec<T>" class that my classes inherit from. in
inherited classes, "thistype" is read at "typeof(*this)".
I suppose I could also rewrite the definition for each class, or use a
macro, but isn't avoiding those the motivation for templates?
treat like vectors (in the mathematical sense); I'd like * and +
operations for scalar multiplication. I also need the std::vector
interface for its dynamic allocation. So, I inherit from std::vector,
and I want to write a function
template<typename S, typename T>
T operator*(const S & op1, const T & op2) {
T ans(op2);
for(typename T::iterator i = ans.begin(); i != ans.end(); ++i) {
i = op1 * *i;
}
return ans;
}
My problem is that this grabs calls for T=<some enum type>. I've
thought of two ways I could prevent this disaster, none of which are
legal C++.
1. I want some sort of bounded polymorphism where T must be a subtype
of vector<S>.
2. I want some sort of "thistype" identifier, so that I can write the
above definition, with "T" replaced by "thistype", and the definition
placed in some "myvec<T>" class that my classes inherit from. in
inherited classes, "thistype" is read at "typeof(*this)".
I suppose I could also rewrite the definition for each class, or use a
macro, but isn't avoiding those the motivation for templates?