【发布时间】:2013-02-07 18:59:23
【问题描述】:
此方法尝试根据键 (std::string) 选择 (std::vector<?>),其中 ? 是 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++ 方法来完成这个?
【问题讨论】:
-
运行时不能选择类型,不行。
auto仍然只在编译时有效。但是,您可以编写两个不同的函数并根据字符串调用正确的函数。 -
@BoPersson 但是编译时不知道可能的字符串(键)。你的想法仍然有效吗?
-
您似乎在
int和float之间进行选择。只需为每个变体编写一个函数,然后调用需要的函数。
标签: c++ c++11 static-typing dynamic-typing