【问题标题】:MPL Map Instantiate TypeMPL 映射实例化类型
【发布时间】:2018-03-30 23:52:47
【问题描述】:

我有以下几点:

class Message
{
public:
    bool process()
    {
        return doProcess();
    }
protected:
    virtual bool doProcess() = 0;
};

class Hello : public Message
{
protected:
    bool doProcess()
    {
        return false;
    }
};
typedef typename boost::mpl::map< boost::mpl::pair< boost::mpl::int_< 0 >, Hello > > map;

struct Generator
{
    typedef void result_type;
    template< typename t_type >
    void operator()(std::vector< boost::shared_ptr< Message > >& processors,
                    t_type p_element)
    {
        typedef typename boost::mpl::at< map, t_type >::type c_instanceType
        boost::shared_ptr< Message > temp(reinterpret_cast< Message* >(new c_instanceType));
        p_processors[p_element] = temp;
    }
};

然后像这样调用:

class MessageProcessor
{
public:
    MessageProcessor() :
        m_processors(12)
    {
        // eventually there will be 12 different messages so I will add
        // them to the mpl map and adjust the range
        boost::mpl::for_each< boost::mpl::range_c< boost::uint8_t, 0, 1 > >
        (
            boost::bind(Generator(), boost::ref(m_processors), _1)
    }
private: 
    std::vector< boost::shared_ptr< Message > > m_processors;
};

这段代码编译干净;但是,当以后像这样调用该函数时:

m_processors[0]->process();

在返回do process 的process 函数中的行发生了分段错误。我正在使用 boost 1.55 版的 gcc 4.8 工作。另请注意,这不是完整的代码。在使用调试器时,我看到调用 doProcess 时 vptr 似乎为空,因此子类似乎不存在。有关如何解决此问题的任何想法?

【问题讨论】:

    标签: c++ boost boost-mpl


    【解决方案1】:

    所以问题似乎是在执行 at 时实际上没有找到该类型,并且返回的是其他东西而不是 Hello 类型。看起来boost::for_each 传入的类型是boost::mpl::integral_c&lt;boost::uint8_t, 0&gt; 类型,它在mpl 映射中不存在,因为我将boost::mpl::int_&lt;0&gt; 存储为键。将映射中的键类型更改为 boost::mpl::integeral_c&lt; boost::uint8_t, 0 &gt; 不会出现段错误并按预期执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多