【问题标题】:Using boost::visitor with a boost::variant of unique_ptr将 boost::visitor 与 unique_ptr 的 boost::variant 一起使用
【发布时间】:2016-10-21 18:47:06
【问题描述】:

我有两种类型的 std::unique_ptr,它们保存在 boost::variant 中。我正在尝试编写 boost::static_visitor 的子类,以提取对我的 boost::variant 模板化的两个 unique_ptr 变体的底层对象的 const 引用。设置如下所示:

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 不是可复制构造的。

【问题讨论】:

  • 您是否尝试过接受参考?

标签: c++ c++11 boost unique-ptr boost-variant


【解决方案1】:

接受对唯一指针的 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

【讨论】:

  • 啊,当然。我对在我的项目中使用智能指针有点陌生,所以我认为传递“对指针的引用”的概念让我感到困惑......
  • @Bitrex 只是将它们视为常规对象。你不能复制一个不可复制的对象,就是这样;)
猜你喜欢
  • 2018-07-21
  • 1970-01-01
  • 2015-05-04
  • 1970-01-01
  • 1970-01-01
  • 2017-12-27
  • 2017-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多