简体   繁体   中英

Can I use BOOST_FUSION_ADAPT_STRUCT with struct consisting of std::vector?

Can i use the " BOOST_FUSION_ADAPT_STRUCT " with a struct type 'opt' having a std::vector ?The std::vector is instantiated with struct type A as below.

Just want to know if this is allowed or I am doing some mistake here while trying to use BOOST_FUSION_ADAPT_STRUCT with a structure containing a std::vector in the use case below?

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))

Sure you can. Macros don't play well with complicated tokens, so add parens.

Note that you don't have to specify the type at all anymore in 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";
    }
}

Prints

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM