taintedwheat@yahoo.com (Gina Yarmel) wrote in message
news:<e4241c19.0308111332.13dba1dd@posting.google. com>...[color=blue]
> 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?[/color]
I don't apprehend your intention but in any case writing such a
template is a bad idea:
1. It catches all multiplication with user types
2. It's implementation isn't generic enough to handle all the
multiplication
(in fact it's not capable of T*S vs S*T)
Though there are ways to check inherritance relations at compile-time
(see SUPERSUBCLASS at moderncppdesign.com, Loki library)
as far as I understand you really want to multiply a scalar value
with 2 kinds of vectors of scalar values. Is it ? Let's try
template<class S> class Vec1 {...} // first vector
template<class S> class Vec2 {...} // second vector
// your implementation renamed
template<typename S, typename T>
T mul_scal_vec(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;
}
// operators
template<class S>
Vec1 operator*(const S& scalar,const Vec1& vector)
{ return mul_scal_vec(scalar,vector); }
template<class S>
Vec2 operator*(const S& scalar,const Vec2& vector)
{ return mul_scal_vec(scalar,vector); }
These operators still catch enum but does it still bother you ?
[ See
http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]