我的问题如下。我正在通过编写图形库来学习 C++,并希望尽可能多地使用通用编程技术;因此,通过“使用 BOOST”回答我的问题对我没有帮助;事实上,我尝试通过 BOOST 的代码来寻找我的问题的答案,但这是一次令人沮丧的经历,因为我什至无法弄清楚某些函数的定义位置;在我的水平上学习它的 C++ 水平太高了。
也就是说,我的库是通过以下方式模板化的:
class edge { ... };
template <class edge_T>
class node { ... };
template <class edge_T, class node_T>
class graph { ... };
我正在通过使用从边或节点派生的类来创建更复杂的图,因此加权边类将很简单
template <class T>
class weighted_edge : public edge {
public:
T weight;
...
};
现在的问题是我想在这个结构上实现一个算法,计算两个顶点之间的最短距离。我可以轻松编写其中的两个,一个用于加权边缘,一个用于未加权,但变化很小:一个将访问weighted_edge
(或派生类)的成员字段,另一个将采用单一权重。
有没有办法做到这一点,这样我就可以在这两种情况下只使用一段代码?
一种解决方案是使用一个成员函数edge::get_weight()
来返回权重(或在未加权的情况下为“1”),但这会迫使我为未加权的边缘类使用特定的权重类型,所以它闻起来很有趣。我的意思是,模板需要是
template <class T>
class edge {
public:
...
virtual T get_weight(void) { return T(1); }
}
这并不完全是用户友好的,或者至少是令人困惑的,因为您不希望涉及任何权重。
BGL 使用get()
函数来获取权重;我可以编写一个返回 1 或weight
取决于的函数edge_T
,但我关心的是当一个从edge
or派生时会发生什么weighted_edge
?如果有人写:
template <class T>
inline T get_weight(edge & e) { return T(1); }
template <class T>
inline T get_weight(weighted_edge & e) { return T(e.weight); }
如果通过派生类会发生什么?是否有 C++ 机制可以从这两个中选择“更接近”的基类?