【发布时间】:2018-06-12 00:22:33
【问题描述】:
所以我正在尝试将 yaml-cpp 与包含指针的数据一起使用,这是我的代码:
struct InventoryItem {
std::string name;
int baseValue;
float weight;
};
struct Inventory {
float maximumWeight;
std::vector<InventoryItem*> items;
};
namespace YAML {
template <>
struct convert<InventoryItem*> {
static Node encode(const InventoryItem* inventoryItem) {
Node node;
node["name"] = inventoryItem->name;
node["baseValue"] = inventoryItem->baseValue;
node["weight"] = inventoryItem->weight;
return node;
}
static bool decode(const Node& node, InventoryItem* inventoryItem) {
// @todo validation
inventoryItem->name = node["name"].as<std::string>();
inventoryItem->baseValue = node["baseValue"].as<int>();
inventoryItem->weight = node["weight"].as<float>();
return true;
}
};
template <>
struct convert<Inventory> {
static Node encode(const Inventory& inventory) {
Node node;
node["maximumWeight"] = inventory.maximumWeight;
node["items"] = inventory.items;
return node;
}
static bool decode(const Node& node, Inventory& inventory) {
// @todo validation
inventory.maximumWeight = node["maximumWeight"].as<float>();
inventory.items = node["items"].as<std::vector<InventoryItem*>>();
return true;
}
};
}
但我收到以下错误:
impl.h(123): error C4700: uninitialized local variable 't' used
引用此代码块中的最后一个 if 语句(此代码在 yaml-cpp 库中:
template <typename T>
struct as_if<T, void> {
explicit as_if(const Node& node_) : node(node_) {}
const Node& node;
T operator()() const {
if (!node.m_pNode)
throw TypedBadConversion<T>(node.Mark());
T t;
if (convert<T>::decode(node, t)) // NOTE: THIS IS THE LINE THE COMPILER ERROR IS REFERENCING
return t;
throw TypedBadConversion<T>(node.Mark());
}
};
有人知道我为什么会收到这个错误吗?
【问题讨论】:
-
那么你只需要
dereference每个item,这是一个pointer类型的Inventory,并将它传递给decode -
@codekaizer 我不手动调用编码/解码,据我了解,这是 yaml-cpp 库调用的东西,所以我不知道我是否(或如何)能够做到那
-
你试过ThorsSerializer 看起来会简单很多。您实际上不需要编写任何代码。 gist.github.com/Loki-Astari/0363c54fcd3db0a144e58e91ee6e0f01
-
哎呀错过了指针的事情。你确定你需要那个吗?除非
InventoryItem是多态的,看起来有点矫枉过正。
标签: c++ pointers yaml yaml-cpp