【问题标题】:Can I use BOOST_FUSION_ADAPT_STRUCT with struct consisting of std::vector?我可以将 BOOST_FUSION_ADAPT_STRUCT 与由 std::vector 组成的结构一起使用吗?
【发布时间】:2022-01-20 07:15:50
【问题描述】:

我可以将“BOOST_FUSION_ADAPT_STRUCT”与具有std::vector 的结构类型“opt”一起使用吗?std::vector 使用结构类型A 进行实例化,如下所示。

只是想知道是否允许这样做,或者我在下面的用例中尝试将BOOST_FUSION_ADAPT_STRUCT 与包含std::vector 的结构一起使用时在这里犯了一些错误?

struct NameValue
{
    NameValue(const std::string& _e) :e(_e)
    {};
    std::string e;
};

struct A
{
    std::string   name;
    boost::optional<bool> value;
    std::string   path;
    std::string   type;
};

BOOST_FUSION_ADAPT_STRUCT(A,
    (std::string, name)
    (boost::optional<bool>, value))
    (std::string, path)
    (std::string, type))        
    

struct opt : public NameValue
{
    opt() : NameValue("One")
    {};
    std::vector<A> s;
};

BOOST_FUSION_ADAPT_STRUCT(opt,
(std::vector<A>, s))

【问题讨论】:

  • 为什么你认为std::vector 会很特别?
  • @Jarod42 - 这里的用例是从特定结构继承的结构中的向量。在我进一步调试我的问题之前,我想检查一下上面共享的 sn-p 是否有问题

标签: c++ boost


【解决方案1】:

当然可以。宏不能很好地处理复杂的标记,所以添加括号。

请注意,在 C++11 中您根本不必再指定类型。

Live On Coliru

#include <boost/fusion/adapted.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/optional.hpp>
#include <boost/optional/optional_io.hpp>
#include <string>
#include <vector>

namespace MyLib {
    struct A {
        std::string           name;
        boost::optional<bool> value;
        std::string           path;
        std::string           type;
    };

    struct NameValue {
        NameValue(std::string e) : e(std::move(e)){};
        std::string e;
    };

    struct opt : public NameValue {
        opt() : NameValue("One"){};
        std::vector<A> s;
    };

    using boost::fusion::operator<<;
} // namespace MyLib

BOOST_FUSION_ADAPT_STRUCT(MyLib::A, name, value, path, type)
BOOST_FUSION_ADAPT_STRUCT(MyLib::opt, s)

#include <iostream>
int main() {
    std::cout << std::boolalpha;
    MyLib::opt o;
    o.s = {
        {"name1", true,        "path1", "type1"},
        {"name2", boost::none, "path2", "type2"},
        {"name3", false,       "path3", "type3"},
    };

    for (auto& el : o.s) {
        std::cout << el << "\n";
    }
}

打印

(name1  true path1 type1)
(name2 -- path2 type2)
(name3  false path3 type3)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
  • 1970-01-01
  • 2013-02-08
  • 2012-05-02
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多