How to get enumeration from boost :: property_tree?

How to get an listing with boost::property_tree?

This is my non-working example.

config.xml

<root>
  <fooEnum>EMISSION::EMIT1</fooEnum>
  <fooDouble>42</fooDouble>
</root>

main.cpp

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

int main()
{
  enum class EMISSION { EMIT1, EMIT2 } ;
  enum EMISSION myEmission;

  //Initialize the XML file into property_tree
  boost::property_tree::ptree pt;
  read_xml("config.xml", pt);

  //test enum (SUCCESS)
  myEmission = EMISSION::EMIT1;
  std::cout << (myEmission == EMISSION::EMIT1) << "\n";

  //test basic ptree interpreting capability (SUCCESS)
  const double fooDouble = pt.get<double>("root.fooDouble");
  std::cout << fooDouble << "\n";

  //read from enum from ptree and assign (FAILURE)
  myEmission = pt.get<enum EMISSION>( "root.fooEnum" );
  std::cout << (myEmission == EMISSION::EMIT1) << "\n";

  return 0;
}

Compile output

/usr/include/boost/property_tree/stream_translator.hpp:36:15: 
error: cannot bind 'std::basic_istream<char>' lvalue to 
'std::basic_istream<char>&&'

/usr/include/c++/4.8/istream:872:5: error:   
initializing argument 1 of 'std::basic_istream<_CharT, 
  _Traits>& std::operator>
(std::basic_istream<_CharT, _Traits>&&, _Tp&)
[with _CharT = char; _Traits = std::char_traits<char>;
_Tp = main()::EMISSION]'
+4
source share
2 answers

The enumeration name in C ++ is a character, not a string. There is no way to match between a string and an enumeration value unless you provide this mapping yourself by writing a method, for example:

EMISSION emission_to_string(const std::string& name)
{
    if ( name == "EMISSION::EMIT1")
    {
        return EMISSION::EMIT1;
    }
    ... etc
}

Then you get the value as a string from the_tree property and apply this mapping.

, . boost:: bimap, enum- > string OR string- > enum, , , if-. , boost:: assign , , .

+5

. , : http://akrzemi1.wordpress.com/2011/07/13/parsing-xml-with-boost/

myEmission = pt.get<EMISSION>("root.fooEnum");
+1

All Articles