使用 boost::visitor 和 boost::variant 的 unique_ptr

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

我有两种类型的 std::unique_ptr,它们都放在 boost::variant 中。我正在尝试编写 boost::static_visitor 的子类来提取对基础对象的 const 引用,我的 boost::variant 的两个 unique_ptr 变体被模板化。设置看起来像这样:

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();
    }
};

我能够在实例化时使用移动语义将 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();
    }
};

这是一个live demo的玩具项目。