2013-03-07 70 views
3
#include <string> 
#include "boost/variant/variant.hpp" 
#include "boost/variant/apply_visitor.hpp" 

using namespace std; 

class Base 
{ 
public: 
    Base(){} 
    ~Base(){} 
    void AddField(int tag, int value){std::cout << "Base::AddField " << tag << ", " << value << std::endl;} 
    void AddField(int tag, string value){std::cout << "Base::AddField " << tag << ", " << value << std::endl;} 
}; 

class A : public Base 
{ 
public: 
    A(){} 
    ~A(){} 
}; 
class B : public Base 
{ 
public: 
    B(){} 
    ~B(){} 
}; 

class foo_visitor 
    : public boost::static_visitor<> 
{ 
public: 
    foo_visitor(int tag){mTag = tag;} 
    template <typename T> 
    void operator()(T &a, int &v) const { 
     a->AddField(mTag, v); 
    } 
private: 
    int mTag; 
}; 

int main(int argc, char **argv) 
{ 
    typedef boost::variant<A*,B*> AB; 
    AB ab = new A();  
    int tag = 1; 
    int v = 2; 
    boost::apply_visitor(foo_visitor(tag), ab, v); 
    return 0; 
} 

我得到這個編譯錯誤:這個二進制文件爲什麼apply_visitor不起作用?

apply_visitor_unary.hpp:60:43: error: request for member ‘apply_visitor’ in ‘visitable’, which is of non-class type ‘int’

這有什麼錯我的代碼?

回答

3

int確實不是variant

Overloads accepting two operands invoke the binary function call operator of the given visitor on the content of the given variant operands.

http://www.boost.org/doc/libs/1_52_0/doc/html/boost/apply_visitor.html

+1

我認爲[這](http://liveworkspace.org/code/MmLUy$0)是什麼Meysam想要的。 – 2013-03-07 12:14:31

+0

@llonesmiz是。而已。請張貼它作爲答案。 – Meysam 2013-03-07 12:17:14

+0

@Meysam我只是按照這個答案的建議。 – 2013-03-07 12:18:13