【问题标题】:Boost.Fusion define struct array memberBoost.Fusion 定义结构体数组成员
【发布时间】:2018-03-20 16:33:08
【问题描述】:

你是怎么做到的?

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]'的值初始化

【问题讨论】:

    标签: c++ boost fusion


    【解决方案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(&amp;)[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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多