2012-11-03 42 views
3

幾天前我開始使用boost庫,所以我的問題可能很簡單。 我想用static_visitor比較兩個相同類型的變體。我嘗試了以下,但它不想編譯。將兩個變體與boost比較static_visitor

struct compare:public boost::static_visitor<bool> 
{ 
    bool operator()(int& a, int& b) const 
    { 
     return a<b; 
    } 

    bool operator()(double& a, double& b) const 
    { 
     return a<b; 
    } 
}; 
int main() 
{ 
    boost::variant<double, int > v1, v2; 
    v1 = 3.14; 
    v2 = 5.25; 
    compare vis; 
    bool b = boost::apply_visitor(vis, v1,v2); 
    cout<<b; 
    return 0; 
} 

謝謝任何​​幫助或建議!

+0

謝謝,它解決了我的問題! – Zozzzzz

+0

@llonesmiz,將其添加爲答案以獲得功勞並關閉問題。 –

回答

1

llonesmiz在評論中告訴我答案,但它消失了。如果有人有類似的問題,它可能會有所幫助: 我不得不處理不同運算符中的int和double的每個組合。最簡單的方法來實現它是使用模板,如下所示:

struct my_less : boost::static_visitor<bool> 
{ 
    template<typename T, typename U> 
    bool operator()(T a, U b) const 
    { 
     return a<b; 
    } 

}; 
+0

'new bool'?如果編譯完成,那麼由於_pointer_到_boolean_的轉換,它總會返回「true」。 –

+0

對不起,我搞砸了......當我使用bool * s時,它出現在我的最終代碼中...我修復了它。 – Zozzzzz