Velocity Reviews > C++ > template and inheritance

# template and inheritance

Olive
Guest
Posts: n/a

 06-20-2008
Hello,

Can you help me on this...
Is there a way to fix the problem at the end of the main?
If the two extra scalar product operator* were defined for scalar types
only, it would be perfect. Can this be possible?

I manage to merge the two first operator* using an is_base_of
type_traits tricks, but I could not fix the friend operator*. And that
was an ugly solution anyway.

Thanks
Olive

struct vect {
int v[3];

//dot product
int operator *(const vect& t) const {
int res = 0;
for (int i = 0; i < 3; ++i)
res += v[i] * t.v[i];
return res;
}
//scalar product
template <typename Y>
vect operator *(const Y& t) const {
vect res;
for (int i = 0; i < 3; ++i)
res.v[i] += v[i] * t;
return res;
}
//scalar product in reverse order (t is the scalar value)
template <typename Y>
friend vect operator *(const Y& t, const vect& v) {
return v*t;
}
};

struct dummy {
};

int main() {
{
vect a;
vect b;
int dot = a*b; // fine
vect c = a*2; // fine
vect d = 2*a; // fine
}
{
dummy a;
dummy b;
int dot = a*b; // the 3 operator* match
dummy c = a*2; // the 3 operator* match
dummy d = 2*a; // the 3 operator* match
}

return 0;
}

Fei Liu
Guest
Posts: n/a

 06-20-2008
Olive wrote:
> Hello,
>
> Can you help me on this...
> Is there a way to fix the problem at the end of the main?
> If the two extra scalar product operator* were defined for scalar types
> only, it would be perfect. Can this be possible?
>
> I manage to merge the two first operator* using an is_base_of
> type_traits tricks, but I could not fix the friend operator*. And that
> was an ugly solution anyway.
>
> Thanks
> Olive
>
> struct vect {
> int v[3];
>
> //dot product
> int operator *(const vect& t) const {
> int res = 0;
> for (int i = 0; i < 3; ++i)
> res += v[i] * t.v[i];
> return res;
> }
> //scalar product
> template <typename Y>
> vect operator *(const Y& t) const {
> vect res;
> for (int i = 0; i < 3; ++i)
> res.v[i] += v[i] * t;
> return res;
> }
> //scalar product in reverse order (t is the scalar value)
> template <typename Y>
> friend vect operator *(const Y& t, const vect& v) {
> return v*t;
> }
> };
>
> struct dummy {
> };
>
> int main() {
> {
> vect a;
> vect b;
> int dot = a*b; // fine
> vect c = a*2; // fine
> vect d = 2*a; // fine
> }
> {
> dummy a;
> dummy b;
> int dot = a*b; // the 3 operator* match
> dummy c = a*2; // the 3 operator* match
> dummy d = 2*a; // the 3 operator* match
> }
>
> return 0;
> }

You can use non class member function templates to achieve the desirable
effects.

Fei