2013-03-03 62 views
1

我正在嘗試boost-variant自定義類。我明白,訪問課程內容的安全方式是使用boost::static_visitor。你知道爲什麼下面的代碼不能編譯?是否有要求使用boost::static_visitor的簽名/聲明?自定義類的提升變體

我發現這個問題Why can't I visit this custom type with boost::variant?但我沒有得到它。

問候

AFG

#include <iostream> 
#include <algorithm> 
#include <boost/variant.hpp> 

struct CA{}; 

struct ca_visitor : public boost::static_visitor<CA> 
{ 
    const CA& operator()(const CA& obj) const { return obj;} 
}; 

struct CB{}; 

struct cb_visitor : public boost::static_visitor<CB> 
{ 
    const CB& operator()(const CB& obj) const { return obj;} 
}; 

int main(){ 
    typedef boost::variant< 
     CA 
     ,CB > v_type; 

    v_type v; 
    const CA& a = boost::apply_visitor(ca_visitor(), v); 
} 

回答

3

首先的boost::static_visitor<>模板參數應指定由操作者調用返回的類型。在你的情況下,ca_visitor的呼叫運營商返回CA const&,而不是CA

但這不是最大的問題。最大的問題是你似乎對variant<>static_visitor<>應該如何工作有誤解。

boost::variant<>的想法是,它可以保存您在模板參數列表中指定類型的任意的值。您不知道該類型是什麼,因此您可以爲訪問者提供幾個重載的呼叫操作員來處理每個可能的情況。

因此,當您提供訪問者時,您需要確保它具有所有必要的重載operator(),它們接受variant可容納的類型。如果你不這樣做,Boost.Variant會導致編譯錯誤的產生(並且正在幫你一個忙,因爲你忘記處理一些情況)。

這是您遇到的問題:您的訪問者沒有接受CB類型對象的呼叫操作員。

這是一個正確的使用和boost::variant<>static_visitor<>的示例:

#include <iostream> 
#include <algorithm> 
#include <boost/variant.hpp> 

struct A{}; 
struct B{}; 

struct my_visitor : public boost::static_visitor<bool> 
//            ^^^^ 
//            This must be the same as the 
//            return type of your call 
//            operators 
{ 
    bool operator() (const A& obj) const { return true; } 
    bool operator() (const B& obj) const { return false; } 
}; 

int main() 
{ 
    A a; 
    B b; 
    my_visitor mv; 

    typedef boost::variant<A, B> v_type; 

    v_type v = a; 

    bool res = v.apply_visitor(mv); 
    std::cout << res; // Should print 1 

    v = b; 

    res = v.apply_visitor(mv); 
    std::cout << res; // Should print 0 
} 
+0

類型由式樣的探視可以通過'T * V來實現=獲得(VAR);'其中'v'如果'var'不是'T'類型的'nullptr'。請注意,這是脆弱的。 – Yakk 2013-03-03 15:35:13

+0

@Yakk:確實,但在我看來,OP在詢問訪問者的正確用法。 – 2013-03-03 15:37:05

+0

當然可以,但我向他們展示瞭如何以他們期望的方式「拜訪」他們的工作方式可能是有用的:很少有人不知道答案知道該問什麼。 – Yakk 2013-03-03 15:47:51