'How to write template class in ruby
I'm true C/C++ programmer and in this moment I'm learning Ruby language.
I'm trying to create template class in ruby, but Ruby didn't have generic classes or interfaces so I had a problem how to write equivalent to followed C++ graph class:
template <class V, class E> struct Graph {
// Graph edges struct
struct Ed : E {
// vertex number
int v;
Ed(E p, int w) : E(p), v(w) { }
};
// Graph vertex that is connected to vector of edges
struct Ve : V, vector<Ed> {};
// Vector of graph vertex that handle connection to other vertex
vector<Ve> g;
}
Idea is to have Graph that vertex and edges inherit from class V and class E.
Graph only should contains vector of existing vertexes, but vertex should be generic because it can be for example city object or geometric lump, and the same is with Edges for example street object.
So my thinking goes to create separate wrappers for each of these classes
def Graph
def initialize(*vertexes)
@vertexes = vertexes
end
end
def Vertex
def initialize(object, *edges)
@o = object
@e = edges
end
end
def Edges
def initialize(object, vertex)
@o = object
@v = vertex
end
end
But if this solution provide access to whole method from Edge and Vertex classes?
For example Edge can be a Street object and street can have its own methods like: speed_limit, capacity or check_availability and I don't know how to handle this case and don't rewrite this methods in wrappers for each Edges and/or Vertex class.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
