How to get enum from boost::property_tree?(如何从 boost::property_tree 获取枚举?)
问题描述
如何从 boost::property_tree
获取枚举?
这是我的非工作"示例.
This is my "non-working" example.
<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) << "
";
//test basic ptree interpreting capability (SUCCESS)
const double fooDouble = pt.get<double>("root.fooDouble");
std::cout << fooDouble << "
";
//read from enum from ptree and assign (FAILURE)
myEmission = pt.get<enum EMISSION>( "root.fooEnum" );
std::cout << (myEmission == EMISSION::EMIT1) << "
";
return 0;
}
编译输出
/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]'
推荐答案
C++ 中枚举的名称是一个符号,而不是字符串.除非您通过编写如下方法自己提供该映射,否则无法在字符串和枚举值之间进行映射:
The name of an enum in C++ is a symbol, not a string. There isn't a way to map between a string and an enum value unless you provide that mapping yourself by writing a method such as:
EMISSION emission_to_string(const std::string& name)
{
if ( name == "EMISSION::EMIT1")
{
return EMISSION::EMIT1;
}
... etc
}
然后,您将从 property_tree 中获取字符串形式的值并应用此映射.
You would then get the value as a string from the property_tree and apply this mapping.
有更好的方法来实现这一点,这些方法可以通过许多枚举值更优雅地扩展.我已经使用 boost::bimap 来启用从 enum->string 或从 string->enum 的映射,当然这也为您提供了一个映射而不是一个愚蠢的大 if 语句.如果您这样做,请考虑使用 boost::assign 来初始化您的静态地图,因为它看起来比其他方法更干净.
There are nicer ways to implement this which scale more elegantly with many enum values. I have done this using boost::bimap to enable a mapping from enum->string OR from string->enum, and of course this also gives you a map instead of a silly big if statement. If you do this, look into using boost::assign to initialise your static map, as it looks cleaner than other methods.
这篇关于如何从 boost::property_tree 获取枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 boost::property_tree 获取枚举?
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01