2011-03-14 9 views
0

私はいくつかのデータをboost :: anyでラップして、クラスメソッドgetValueのマップに貼り付けています。すべて正常に動作し、データはgetValueの適切なものなどのマップにあります。 2番目はgetValueを残して、このデータを使用しようとしましたが、マップにはもうありません。std :: map私のデータのトラックを失う?

これは私を困惑させました。キーポイントでリファレンスを使用するのを忘れているかもしれませんが、見つけられません。次のように

関連するコードは次のとおりです。

test.cの 私たちが実際にタイマーを文書化する必要はありません//、ユーザーは自分がしたい場合はそれを行うことができます。 timeval tmp;あなたがvmap代わりのgmapを使用するこれらのラインに

tmp.tv_sec = 0; 
    tmp.tv_usec = 0; 

    gettimeofday(&tmp, NULL); 
    getValue<timeval>(timerName) = tmp; 
    std::cout << tmp.tv_usec << " : " << getSingleton().globalValues.count(key) << std::endl; //Count returns 0 here, for a given key X_X 

TEST.H

/* Grab the value of type T found while parsing. Should use checkValue first.*/ 
    template<typename T> 
    static T& getValue(const char* identifier) { 
    //Used to ensure we have a valid value 
    T tmp; 
    //Used to index into the globalValues map 
    std::string key = std::string(identifier); 
    std::map<std::string, boost::any>& gmap = getSingleton().globalValues; 

    if(checkValue(identifier)) //If we have the option, set it's value 
     tmp = getSingleton().vmap[identifier].as<T>(); //vmap is correct, it specifies default values passed in via command line. 

    //We may have whatever is on the commandline, but what if 
    //The programmer has made modifications? 
    if(!gmap.count(key)) //The programmer hasn't done anything, lets register it then 
     gmap[key] = boost::any(tmp); 

    std::cout << "gmap " << key << std::endl;   
    std::cout << getSingleton().globalValues.count(key) << std::endl; //count returns 1 here, for a given key. 
    return boost::any_cast<T&>(gmap[key]); 
    } 

...

TEST.H

//Map of global values, stored here instead of in OptionsHierarchy 
    //For ease of implementation 
    std::map<std::string, boost::any> globalValues; 
+5

ローカル変数への参照を返す??? –

+0

「boost boost :: any_cast (gmap [key]);」のように聞こえます。 boost :: anyに格納されている値への参照を返します。 – mamidon

+0

あなたの地図gmapのTの参照にany_castを行っています。これはローカルの変数です(あなたのマップの値もローカルです)。 .. –

答えて

0

これを修正しました.getValueでkeyをstd :: string(identifier)として定義する方法に注意してください。私はsanitizeString(..)としてキーを定義していましたが、明らかに別のキーを返しました。もちろん、皆さんは私の悪いことを見ることができませんでした。

0

。そうですか?

if(checkValue(identifier)) //If we have the option, set it's value 
    tmp = getSingleton().vmap[identifier].as<T>(); 

はまた、私はあなたがアイテムの存在を確認するためにcountを使用していることに気づきました。一般的に言えば、実際にカウントが必要な場合を除き、std::mapについてはcountfindに最適化するのに十分なほどスマートになるかもしれませんが、それはfindより多くの仕事をするでしょう。存在しない場合は挿入したい場合は挿入したい場合は、insertをそのまま使用してください。つまり、insertが表示されます。

+0

vmapは、コマンドラインで定義された省略可能なデフォルト値用です。 – mamidon

+1

'std :: map'の場合、' count'を使用するとより簡単にメンバーシップをチェックできます。 'count'は' 0'または '1'だけを返すことができるという知識で実装されているので、少なくともfindと同じくらい効率的です。 –

関連する問題