【发布时间】:2016-12-09 18:30:06
【问题描述】:
我有一个yaml-cpp,它总是转换成std::string,有时也转换成别的东西。例如,如果字符串实际上是"3.14",它也会转换为double。我首先想尝试int,然后是double,然后是bool,如果这不起作用,请转换为std::string。好吧,让我们嵌套那些try-catches:
try {
const int a = node.as<int>();
std::cout << "int!" << a << std::endl;
} catch (YAML::BadConversion) {
try {
const double a = node.as<double>();
std::cout << "double!" << a << std::endl;
} catch (YAML::BadConversion) {
try {
const bool a = node.as<bool>();
std::cout << "bool!" << a << std::endl;
} catch (YAML::BadConversion) {
const std::string a = node.as<std::string>();
std::cout << "string!" << a << std::endl;
}
}
}
嗯,越来越深的嵌套告诉我,这不是编写该代码的最佳方式。
关于如何改进这里的设计有什么建议吗?当然建议使用平面嵌套。
【问题讨论】:
-
不确定,只是尝试一下 {} 和 catch(...)?然后通过一个函数检查Exception...Like ExceptionStatement(Exception e)。