0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[boost::property_tree] second.get_optional()を使用する際の存在チェックについて

Posted at

解決法

boost::noneで存在チェックを行う

if(obj->second.get_optional<std::string>("<xmlattr>.type") == boost::none)
    continue;
auto type = obj->second.get_optional<std::string>("<xmlattr>.type");

詳細

xmlファイルはboostライブラリのproperty_treeで読み込むことができる。
例えば

<node name="b_Root" id="b_Root" sid="b_Root" type="JOINT">
</node>

という記述があったとして、type属性を読み込むには

auto type = obj->second.get_optional<std::string>("<xmlattr>.type");

などとすれば取得できるが、もしnodeにtype属性がなかった場合上記関数を実行するとランタイムエラーとなり、プログラムが停止してしまうので、あらかじめ属性の存在チェックを行っておく必要がある。
get_optionalのコメント文には

boost::null

と記載されているが、正しくは

boost::none

を用いることによって存在チェックが行える。
参考:
https://boostjp.github.io/tips/optional.html

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?