Search code examples
c++boostboost-propertytree

Can this boost ptree block be shorter (and smarter)?


I'm creating a JSON string exploiting boost ptree library but I'm finding it tedious just by doing the following. I need to add a simple array like "metric.name" : [A, B] to the metrics ptree. Can I do better than this? Or at least write this in a cleaner way.

      pt::ptree metric_avg;
      metric_avg.put("", 9999);
      pt::ptree metric_std;
      metric_std.put("", 0);
      pt::ptree metric_distr;
      metric_distr.push_back({"", metric_avg});
      metric_distr.push_back({"", metric_std});
      metrics.add_child(metric.name, metric_distr);

Solution

  • I'd write some helper functions

    template<typename T>
    pt::ptree scalar(const T & value)
    {
        pt::ptree tree;
        tree.put("", value);
        return tree;
    }
    
    template<typename T>
    pt::ptree array(std::initialiser_list<T> container)
    {
        pt::ptree tree;
        for (auto & v : container)
        { 
            tree.push_back(scalar(v));
        }
        return tree;
    }
    

    That way you can write

    metrics.put(metric.name, array({ 9999, 0 }));