此方法尝试std::vector<?>
根据键 ( ) 选择 ( std::string
),其中?
是int
或float
:
template<typename L>
inline void EnsembleClustering::Graph::forNodesWithAttribute(std::string attrKey, L handle) {
// get nodemap for attrKey
auto nodeMap; // ?
auto findIdPair = this->attrKey2IdPair.find(attrKey);
if (findIdPair != this->attrKey2IdPair.end()) {
std::pair<index, index> idPair = findIdPair->second;
index typeId = idPair.first;
index mapId = idPair.second;
// nodemaps are in a vector, one for each node attribute type int, float, NodeAttribute
switch (typeId) {
case 0:
nodeMap = this->nodeMapsInt[mapId];
break;
case 1:
nodeMap = this->nodeMapsFloat[mapId];
break;
}
// iterate over nodes and call handler with attribute
this->forNodes([&](node u) {
auto attr = nodeMap[u];
handle(u, attr);
});
} else {
throw std::runtime_error("node attribute not found");
}
}
该类的相关成员是:
std::map<std::string, std::pair<index, index>> attrKey2IdPair; // attribute key -> (attribute type index, attribute map index)
// storage
std::vector<std::vector<int> > nodeMapsInt; // has type id 0
std::vector<std::vector<float> > nodeMapsFloat; // has type id 1
这将无法编译,因为auto nodeMap
(= std::vector<?>
) 未初始化。但是为了初始化它,我必须在编译时知道它的类型。
也许我正在尝试的事情不能用静态类型来完成。有没有 C++ 方法来完成这个?