Here’s my problem: I wrote two base classes: Wire and CircuitComponent. The two were almost similar enough to derive from a common superclass, but not. Wire can only join with CircuitComponent, and CircuitComponent can only join with wire. The implementations were identical aside from type though, so naturally I thought templates were the answer.
Here’s the template, and I have a Wire class that derives from TwoTypeMesh<Wire, CircuitComponent> and a CircuitComponent class that derives from TwoTypeMesh<CircuitComponent, Wire> :
template <class thisType, class otherType>
class TwoTypeMesh {
std::set<otherType *> neighbors;
public:
void join(otherType * n){
if (neighbors.find(n) != neighbors.end()) {
return;
} else {
neighbors.insert(n);
n->join(this);
}
}
void disconnect(otherType * n){
if (neighbors.find(n) == neighbors.end()) {
return;
} else {
neighbors.erase(n);
n->disconnect(this);
}
}
};
Problem is I can’t get it to compile, it complains about the line with n->join(this) cause this is of type TwoTypeMesh<Wire, CircuitComponent> (the superclass of Wire) but join is only defined for a wire.
My best theory thus far is that I shouldn’t be subclassing, maybe typedef, but I haven’t managed to make it work yet.
The minimally-invasive way to make your code compile is indeed to use a typedef, and either tag classes, or simply Enumerations: