【发布时间】:2023-03-24 05:25:01
【问题描述】:
我需要用其他对象提供的装饰反序列化 std::vector<boost::variant<..>>。
“装饰”启用的一件事是向量中的一个空条目。我在实际实施中遇到了障碍。但是,我设法将其收缩包装。编译代码:
#include <string>
#include <boost/spirit/include/karma.hpp>
#include <boost/variant.hpp>
#include <boost/cstdint.hpp>
namespace karma = boost::spirit::karma;
typedef boost::variant<boost::int32_t, boost::int64_t> custom_variant;
int main()
{
using karma::generate;
custom_variant v;
std::string temp;
std::back_insert_iterator<std::string> x(temp);
std::cout << v;
karma::generate(x, karma::auto_, v);
}
有问题的更改尝试实现“未定义”类型以及所需的概念。
#include <string>
#include <boost/spirit/include/karma.hpp>
#include <boost/variant.hpp>
#include <boost/cstdint.hpp>
namespace karma = boost::spirit::karma;
struct undefined{};
std::ostream & operator<<(std::ostream & out, undefined const & undefined)
{
return out;
}
typedef boost::variant<undefined,boost::int32_t, boost::int64_t> custom_variant;
int main()
{
using karma::generate;
custom_variant v;
std::string temp;
std::back_insert_iterator<std::string> x(temp);
std::cout << v;
karma::generate(x, karma::auto_, v);
}
如果我注释掉karma::generate 步骤,std::cout 是一个有效的表达式(Boost::variant OutputStreamable)。 Spirit 要求生成器的类型为 OutputStreamable(spirit::karma OutputStreamable) 并且上面的变体应该是 OutputStreamable 因为我已将 undefined typeOutputStreamable 作为无操作。
什么给了? :(
我真的开始质疑 C++ 模板机制在使用具有 > 2 级模板间接的库时是否值得。也许我应该回到直接-c。
编辑 1:
好的,Clang 给了我一个明智的first 错误...
error: no type named 'properties' in 'boost::spirit::karma::no_auto_mapping_exists'
现在我要弄清楚如何将 undefined 映射为无操作来获得干净的转换。这个spirit documentation entry(以及具体的this)描述了我需要研究的内容。是否存在由 Spirit 提供的通用未定义类型或在 boost 中定义的类型,该 Spirit 已经映射为 no-op ?
编辑 2:
std::vector<boost::optional<boost::variant<..>>> 开始看起来很有吸引力,因为精神为他们提供了类型推断。
【问题讨论】:
标签: c++ boost-spirit boost-variant boost-spirit-karma