2016-08-03 7 views
-2

私は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; 
    } 
    } 
} 

フム、深く深くネストが、これはそのコードを記述するための最良の方法ではないことを私に伝えます。

ここでデザインを改善する方法についてのご意見はありますか?フラットネストは確かに推奨されるでしょう。
は、単一のtry-catch内
すべてなど、ブール値を試行し、文字列にに変換し、例外を無視:

+0

わからないが、ただ一つのtry {}とキャッチ(...)をさらに簡素化することができ

int anInt; double aDouble; bool aBool; if (YAML::convert <int>::decode (node, anInt)) std::cout << "int!" << anInt << std::endl; else if (YAML::convert <double>::decode (node, aDouble)) std::cout << "double!" << aDouble << std::endl; else if (YAML::convert <bool>::decode (node, aBool)) std::cout << "double!" << aBool << std::endl; else std::cout << "string!" << node.as <std::string>() << std::endl; 

? ExceptionStatement(Exception e)のように、Exceptionを関数でチェックします。 –

答えて

4

あなたは次のように関数の中でそれを置いてもよい

int a; 
double d; 
bool b; 
std::string s; 
if (tryParseNode(node, a) { 
    std::cout << "int!" << a << std::endl; 
} 
else if (tryParseNode(node, d) { 
    std::cout << "double!" << d << std::endl; 
} 
else if (tryParseNode(node, b) { 
    std::cout << "bool!" << b << std::endl; 
} 
else if (tryParseNode(node, s) { 
    std::cout << "string!" << s << std::endl; 
} 
2

は、他の方法でラウンドしてみてください。その後、

template<typename N, typename T> 
bool tryParseNode(N& node, T& val) { 
    try { 
    val = node.as<T>(); 
    return true; 
    } catch (YAML::BadConversion) { 
    return false; 
    } 
} 

+0

いいアイデア、ありがとう! –

1

の例外を使用して、通常の制御フローのために悪い習慣と考えられています。この場合、asメソッドは `YAML :: convert :: decode 'メソッドを使用してノードを要求された型に変換しようとします。例外をスローする代わりに失敗した場合はfalseを返します。

template <typename value_type> 
std::optional <value_type> decode (YAML::Node const & Node) 
{ 
    value_type Value; 

    if (YAML::convert <value_type>::decode (node, Value)) 
     return { Value }; 
    else 
     return {}; 
} 

if (auto anInt = decode <int> (node)) 
    std::cout << "int!" << *anInt << std::endl; 
else 
if (auto aDouble = decode <double> (node)) 
    std::cout << "double!" << *aDouble << std::endl; 
else 
if (auto aBool = decode <bool> (node)) 
    std::cout << "double!" << *aBool << std::endl; 
else 
    std::cout << "string!" << node.as <std::string>() << std::endl; 
関連する問題