template and inheritance

O

Olive

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 * t.v;
return res;
}
//scalar product
template <typename Y>
vect operator *(const Y& t) const {
vect res;
for (int i = 0; i < 3; ++i)
res.v += v * 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;
}
 
F

Fei Liu

Olive said:
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 * t.v;
return res;
}
//scalar product
template <typename Y>
vect operator *(const Y& t) const {
vect res;
for (int i = 0; i < 3; ++i)
res.v += v * 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top