2016-10-21 27 views
2

我有兩種類型的std :: unique_ptr,它們被保存在boost :: variant中。我試圖編寫一個boost :: static_visitor的子類,以提取一個const引用到底層對象,我boost :: variant模板化的兩個unique_ptr變體。設置看起來是這樣的:使用boost :: visitor與unique :: _ ::的一個boost ::變體

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爲對象的升壓::變種成員變量的實例。但是,當我嘗試使用上述訪問者訪問變體類型時,編譯器會抱怨它無法執行,因爲unique_ptr不是可複製構造的。

+3

您是否嘗試接受參考? – krzaq

回答

2

接受對唯一指針的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

+0

啊,當然。我在我的項目中使用智能指針有點新,所以我認爲傳遞「引用指針」的概念讓我絆倒了...... – Bitrex

+1

@Bitrex只是將它們視爲常規對象。你不能複製一個不可複製的對象,就是這樣;) – krzaq