Templated operator overloading with nested classes

Jul 18, 2008 at 6:11pm
 I’m writing code for a positioning system, and I’m trying to apply some dimensional type-checking. The class structure I’m trying looks like (constructors &c. elided for space):
1
2
3
4
5
6
struct vector {
	double x; double y;
	struct diff {double x; double y;};
};
struct position : public vector {};
struct velocity : public vector {};
to which I’d like to add overloaded operators of the form:
1
2
3
4
template <class V>
V operator + (const V& lhs, const V::diff& rhs {
	return V(lhs.x+rhs.x, lhs.y+rhs.y);
}
—but I can’t quite get this to work; the compiler complains of “expected unqualified-id before ‘&’ token”.
 How might I accomplish what I’m aiming at? Will operator overloading in the base class carry over to the derived classes. (And before anyone asks: Yes, I do have need to discriminate a ‘position’ p from a ‘distance’ d.)
Jul 19, 2008 at 6:03pm
What is that you are using in the function declaration, V::diff ???

Is it a type or some thing ?

The declaration requires you to specify the type of object/parameter it receives. Seems you have to come from that corner, what is "diff" in V class/object?

And another thing, a template would be a generic. But the thing "diff" makes it look like specialized. Meaning, what about a type you pass to the template that does not have a "diff" thing?

Check it out. Good luck :)
Jul 21, 2008 at 3:27pm
You just have to use typename to tell the compiler that V::diff is really a type and not a variable...

1
2
3
V operator + (const V& lhs, const typename V::diff& rhs){
	return V(lhs.x+rhs.x, lhs.y+rhs.y);
}

On my computer with suitable constructors, it compiles fine.
Topic archived. No new replies allowed.