2013-02-26 4 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; 
}; 

そして、次のように私はそれを使用しています:私は単純なクラスを実装するので、私は、ラムダ式を使用することはできません

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

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

を私は_found = sにブレークポイントを設定した場合、私はその_foundを確認することができますセットを取得していますしかし、search.found()は常に空文字列を返します。私はそれが、functorがfor_eachの中で呼び出されている方法と関係があると推測していますが、わかりません。

私は間違っていますか?

+2

nitpick:メンバ変数が綴られるべき* _sought * * * _saughtない:) – Praetorian

答えて

5

それは

  • 文字列の実際の値は、元のように(無駄なステートフルファンクタを作る、ファンクタは値によって渡される

  • (低い)空の文字列であることが考えられ状態は実際には渡されません)。

あなたは_foundフィールド(それを動作させるために、ルール・オブ・スリーを尊重することを確認するためにあなたを必要とする)参照作ることができます。

ここSymbolSearcherを経由して往復の結果をアサートすることによって原理を示すデモです: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完全に働く[ライブワークスペースのデモンストレーション](http://liveworkspace.org/code/4qupWC$1) – sehe

関連する問題