2013-02-26 3 views
5

내가 심볼 테이블이있는 경우 :검색 중/순회 부스트 :: 정신 :: 치 :: 문자

struct MySymbols : symbols<char, MyEnum::Fruits> 
{ 
    MySymbols() 
     : symbols<char, MyEnum::Fruits>(std::string("MySymbols")) 
    { 
     add("apple", MyEnum::Apple) 
      ("orange", MyEnum::Orange); 
    } 
}; 

나는 데이터 값을 기준으로 심볼을 검색하기 위해 테이블을 반복 할을. 나는 간단한 클래스 구현 그래서 나는 람다 표현식을 사용할 수 없습니다

template<typename T> 
struct SymbolSearcher 
{ 
    SymbolSearcher::SymbolSearcher(T searchFor) 
     : _sought(searchFor) 
    { 
     // do nothing 
    } 

    void operator() (std::basic_string<char> s, T ct) 
    { 
     if (_sought == ct) 
     { 
      _found = s; 
     } 
    } 

    std::string found() const { return _found; } 

private: 
    T _sought; 
    std::string _found; 
}; 

을 다음과 같이 나는 그것을 사용하고 있습니다 : 나는 _found = s에 브레이크 포인트를 설정하면

SymbolSearcher<MyEnum::Fruits> search(ct); 
MySymbols symbols; 

symbols.for_each(search); 
std::string symbolStr = search.found(); 

내가 그 _found을 확인할 수 있습니다 설정지고 그러나 search.found()는 항상 빈 문자열을 반환합니다. 나는 functor가 for_each 내부에서 호출되는 방식과 관련이 있다고 추측하고 있지만 모르겠습니다.

내가 뭘 잘못하고 있니?

+2

nitpick : 멤버 변수의 철자해야 * _sought *하지 * _saught * : – Praetorian

답변

5

그것은

  • 문자열의 실제 값이 원본과 (쓸모 상태 펑를 만드는 펑이 값에 의해 전달되는

  • (가능성)이 빈 문자열 일 수 있었다 상태는 실제로 전달되지 않습니다).

당신은 _found 필드 참조 할 수있다 (당신이 그것을 작동하게하는 규칙의-세를 존중해야 할 필요). http://liveworkspace.org/code/4qupWC$1

#include <boost/spirit/include/qi.hpp> 

namespace qi  = boost::spirit::qi; 

template<typename T> 
struct SymbolSearcher 
{ 
    SymbolSearcher(T searchFor, std::string& result) : _sought(searchFor), _found(result) 
    { 
    } 

    void operator() (std::basic_string<char> s, T ct) 
    { 
     if (_sought == ct) 
     { 
      _found = s; 
     } 
    } 

    std::string found() const { return _found; } 

private: 
    T _sought; 
    std::string& _found; 
}; 

int main() 
{ 
    const std::string str("mies"); 

    typedef std::string::const_iterator It; 
    It begin = str.cbegin(); 
    It end = str.cend(); 

    qi::symbols<char, int> symbols; 
    symbols.add("aap", 1)("noot", 2)("mies", 3); 

    int out; 
    bool ok = qi::parse(begin, end, symbols, out); 
    assert(ok); 

    std::string found; 
    SymbolSearcher<int> sf(out, found); 
    symbols.for_each(sf); 

    assert(str == sf.found()); 
} 
+0

추가 a를 여기

SymbolSearcher를 통해 왕복의 결과를 주장하여 원리를 보여주는 데모입니다 [liveworkspace 데모] (http://liveworkspace.org/code/4qupWC$1) – sehe