我的程序中有一个boost :: variant,它包含double
,uint16_t
,std::string
等类型。我正在存储这些,我想使用{ {1}}生成/打印出来。我是boost::karma
的新手,但我知道它适用于变体。我有什么选择呢?简单的语法/规则会产生什么样的?任何帮助都会很棒!
答案 0 :(得分:2)
我能想到的绝对最简单的例子,展示业力甚至可以为您的特定变体动态合成auto_
规则 [1] :
#include <boost/spirit/include/karma.hpp>
namespace karma = boost::spirit::karma;
int main() {
typedef boost::variant<double, unsigned int, std::string> V;
for(auto v : { V{42u}, V{3.1416}, V{"Life Of Pi"} })
std::cout << karma::format(karma::auto_, v) << "\n";
}
打印:
42
3.142
Life Of Pi
简单就是馅饼!
单独语法中的等效词: Live On Coliru
更复杂的语法(也是 Live On Coliru ),它向您展示了Spirit的属性兼容性如何规范DoTheRightThing™:
#include <boost/spirit/include/karma.hpp>
namespace karma = boost::spirit::karma;
typedef boost::variant<double, unsigned int, std::string> V;
struct gen : karma::grammar<boost::spirit::ostream_iterator, V()> {
gen() : gen::base_type(start)
{
using namespace karma;
start = my_real | my_uint | my_text;
my_uint = "The value is unsigned integral value (" << uint_ << ")";
my_real = "The value is double precision floating point value (" << double_ << ")";
my_text = "The value is an epos: '" << *quoted_char << "'";
quoted_char = '\\' << char_("'") | graph | "\\x" << uint_generator<uint8_t, 16>();
}
private:
karma::rule<boost::spirit::ostream_iterator, V()> start;
karma::rule<boost::spirit::ostream_iterator, double()> my_real;
karma::rule<boost::spirit::ostream_iterator, unsigned int()> my_uint;
karma::rule<boost::spirit::ostream_iterator, std::string()> my_text;
karma::rule<boost::spirit::ostream_iterator, uint8_t()> quoted_char;
};
int main()
{
for(auto v : { V{42u}, V{3.1416}, V{"It's a beautiful day!"} })
std::cout << karma::format(gen(), v) << "\n";
}
打印:
The value is unsigned integral value (42)
The value is double precision floating point value (3.142)
The value is an epos: 'It\'s\x20a\x20beautiful\x20day!'
main
也可以写成
int main() {
std::cout << karma::format(gen() % "\n", std::vector<V>{42u,3.1416,"It's a beautiful day!"}) << "\n";
}
这应该可以让您了解Spirit Parser / Generator框架的多功能性。
[1] 只要存在自动解析器生成器特征; Spirit为各种类型提供了它们,包括uint
,std::string
,double
和variant
(还包括选项,矢量,地图,任何可以作为Fusion修改的内容)序列等等。)