Boost.Fusion定义struct数组成员

时间:2018-03-20 16:33:08

标签: c++ boost fusion

你是怎么做到的?

using char10 = char[10];  
BOOST_FUSION_DEFINE_STRUCT(
    (demo), employee,
    (char10, name))

不起作用:
main.cpp:8:1:错误:将'boost :: call_traits :: param_type {aka const char * const}'赋值给'char10 {aka char [10]}'

的不兼容类型
using char10 = char[10];
BOOST_FUSION_DEFINE_STRUCT(
    (demo), employee,
    (decltype(char10{}), name))

也不起作用:
main.cpp:8:1:错误:引用类型'char(&)[10]'的值初始化

1 个答案:

答案 0 :(得分:1)

对于C风格的数组来说这是不可能的,因为C具有臭名昭着的数组到指针衰减属性(并且仍然为了向后兼容性而绑定C ++)。

这会中断,因为Fusion宏会生成如下代码:

namespace demo {
    struct employee {
        typedef employee self_type;
        char10 name;
        employee() : name() {}
        employee(self_type const &) = default;
        employee(self_type &&) = default;
        template <typename Seq>
            employee(Seq const &seq, typename boost::disable_if<boost::is_convertible<Seq const &, char10> >::type * = 0)
            : name(boost::fusion::deref(boost::fusion::advance_c<0>(boost::fusion::begin(seq)))) {}
        self_type &operator=(self_type const &) = default;
        self_type &operator=(self_type &&) = default;
        template <typename Seq> self_type &operator=(Seq const &seq) {
            typedef typename boost::fusion::result_of::begin<Seq const>::type I0;
            I0 i0 = boost::fusion::begin(seq);
            name = boost::fusion::deref(i0);
            return *this;
        }
        explicit employee(boost::call_traits<char10>::param_type arg) : name(arg) {}
    };
} // namespace demo

在构造函数的初始化列表中:

explicit employee(boost::call_traits<char10>::param_type arg) : name(arg) {}

arg的类型将是char const*,它不是字符串的有效初始化程序(char const(&)[10]会是,但需要

解决方案

采用C ++方式:

Live On Coliru (c ++ 11)

#include <boost/fusion/include/define_struct.hpp>

using char10 = std::array<char, 10>;

BOOST_FUSION_DEFINE_STRUCT(
    (demo), employee,
    (char10, name))

#include <boost/core/demangle.hpp>
#include <iostream>
int main() {
    demo::employee emp;
    emp.name = {{'I',' ','a','m',' ','G','r','o','o','t'}};
}

如果您陷入黑暗时代,可以使用boost::array代替:

Live On Coliru (c ++ 03)

相关问题