我有一個yaml-cpp,它總是轉換成std::string
,有時也轉換成別的東西。例如,如果字符串實際上是"3.14"
,它也會轉換爲double
。我首先想要嘗試int
,然後double
,然後bool
,如果不起作用,請轉換爲std::string
。好吧,讓我們這些窩try
- catch
ES:乘以嵌套try-catch
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(...)?然後通過一個函數檢查異常...像ExceptionStatement(Exception e)。 –