使用boost::visitor和unique_ptr的boost::变体

Using boost::visitor with a boost::variant of unique_ptr

本文关键字:boost ptr 变体 visitor 使用 unique      更新时间:2023-10-16

我有两种std::unique_ptr类型,它们保存在boost::变量中。我正试图编写boost::static_visitor的子类,以提取对底层对象的两个unique_ptr变体的const引用,我的boost::variant是模板化的。设置看起来像这样:

using bitmap_flyweight_t = boost::flyweights::flyweight<allegro_bitmap_t>;
using image_bitmap_flyweight_t = boost::flyweights::flyweight<boost::flyweights::key_value<const char*, allegro_bitmap_t>>;
class bitmap_visitor : public boost::static_visitor<allegro_bitmap_t>
{
public:
    const allegro_bitmap_t& operator()(const std::unique_ptr<bitmap_flyweight_t> bitmap_ptr) const
    {
        return bitmap_ptr.get()->get();
    }
    const allegro_bitmap_t& operator()(const std::unique_ptr<image_bitmap_flyweight_t> bitmap_ptr) const
    {
        return bitmap_ptr.get()->get();
    }
};

我可以在实例化时使用move语义将unique_ptrs放入对象的boost::variant成员变量中,没有编译器抱怨。然而,当我尝试使用上述访问器访问变量类型时,编译器抱怨它不能这样做,因为unique_ptr不是可复制构造的。

接受唯一指针的const引用。

class bitmap_visitor : public boost::static_visitor<allegro_bitmap_t>
{
public:
    const allegro_bitmap_t& operator()(const std::unique_ptr<bitmap_flyweight_t>& bitmap_ptr) const
    {
        return bitmap_ptr.get()->get();
    }
    const allegro_bitmap_t& operator()(const std::unique_ptr<image_bitmap_flyweight_t>& bitmap_ptr) const
    {
        return bitmap_ptr.get()->get();
    }
};

这是一个玩具项目的实时演示。