3 ms·
You just moved the problem. Suppose you have two "add" functions: one for fractions, one for points: Fraction add(Fraction a, Fraction b) { Fraction r
by Ace17 10y ago
You just moved the problem.
Suppose you have two "add" functions: one for fractions, one for points:
Fraction add(Fraction a, Fraction b)
{
Fraction result;
result.num = a.num * b.denom + b.num * a.denom;
result.denom = a.denom * b.denom;
return result;
}
Point add(Point a, Point b)
{
Point result;
result.x = a.x + b.x;
result.y = a.y + b.y;
return result;
}
How would you write this in C++?
Obviously the code below won't do:
union_t<int> add_fractions(union_t<int> a, union_t<int> b);
union_t<int> add_points(union_t<int> a, union_t<int> b);
Because you now just lost type safety (i.e you can add fractions with points).
To get back strong type safety, you could write:
struct Fraction : public union_t<int> {};
struct Point : public union_t<int> {};
At this point, you're mostly back to square one, except that Fraction users must use members named "x" and "y" ...
(and I'm not even talking about operator overloading)
(By the way, "union" is an unfortunate choice of words, as the language already defines it to mean something completetly different. Maybe "pair" is more appropriate?).