2012-11-07 3 views
2
나는 다음과 같은 컴파일러 오류를 얻고있다

에서 작동하지 않는 다음 코드를부스트 : 왜 apply_visitor이 코드

/usr/include/boost/variant/variant.hpp:832:32: error: no match for call to ‘(const StartsWith) (bool&)’

. 왜 아무도 알지 못해?

#include "boost/variant/variant.hpp" 
#include "boost/variant/apply_visitor.hpp" 

using namespace std; 
using namespace boost; 

typedef variant<bool, int, string, const char*> MyVariant; 

class StartsWith 
    : public boost::static_visitor<bool> 
{ 
public: 
    string mPrefix; 
    bool operator()(string &other) const 
    { 
     return other.compare(0, mPrefix.length(), mPrefix); 
    } 
    StartsWith(string const& prefix):mPrefix(prefix){} 
}; 

int main(int argc, char **argv) 
{ 
    MyVariant s1 = "hello world!"; 
    apply_visitor(StartsWith("hel"), s1); // << compiler error 
    return 0; 
} 

답변

3

MyVariant에 선언 된 모든 유형에 대해 연산자를 제공해야합니다.

+0

그래, 그리고 정확히 그 static_visitor의 장점, 타입 안전의 핵심 아이디어. –

+0

나는 그것을 고쳤다. 고맙습니다! 'StartsWith' 방문자는 두 문자열을 비교하기위한 것이고, 다른 타입에 대해서는 false를 반환해야하기 때문에 false를 반환하는 다른 유형에 대해서만 하나의 단일 함수를 갖는 방법이 있다고 생각합니까? 어쩌면 템플릿을 사용하여? – Meysam

+0

예 템플릿 방법 http://www.boost.org/doc/libs/1_52_0/doc/html/variant/tutorial.html에 대한 내용을 읽을 수 있습니다. –