代码之家  ›  专栏  ›  技术社区  ›  AndreasT

基于std::map和boost::any:转换错误的数据存储库

  •  0
  • AndreasT  · 技术社区  · 14 年前

    我的一个小程序的知识库。 我使用boost::any的std::map来保存不同的 信息。为了调试和安全起见,我 数据的额外安全访问器“”getVal()“”。

    一个片段说了一千多个字:

    #include <map>
    #include <boost/any.hpp>
    #include <boost/shared_ptr.hpp>
    #include <string>
    #include <iostream>
    
    typedef std::map<int, boost::any> KnowledgeBase_base;
    /**
     *  * KnowledgeBase is simply a storage for information,
     *   * accessible by key.
     *    */
    class KnowledgeBase: public KnowledgeBase_base
    {
        public:
            template<typename T>
                T getVal(const int idx)
                {
                    KnowledgeBase_base::iterator iter = find(idx);
                    if(end()==iter)
                    {
                        std::cerr << "Knowledgebase: Key " << idx << " not found!";
                        return T();
                    }
                    return boost::any_cast<T>(*iter);
                }
    
            bool isAvailable(int idx)
            {
                return !(end()==find(idx));
            }
    
        private:
    };
    
    int main(int argc, char** argv)
    {
        KnowledgeBase kb;
        int i = 100;
        kb[0] = i;
        kb[1] = &i;
    
        std::cout << boost::any_cast<int>(kb[0]) << std::endl; // works
        std::cout << *boost::any_cast<int*>(kb[1]) << std::endl; // works
        std::cout << kb.getVal<int>(0) << std::endl; // error
        std::cout << kb.getVal<int*>(1) << std::endl; // error
        std::cout << "done!" << std::endl;
            return 0;
    }
    

    当我储存 Something* 在里面,试试看
    编辑:正如上面更新的示例代码所示,它不需要是指针! boost::exception\u detail::clone\u impl>'

    如果我使用KnowledgeBase::operator[],它就可以工作。 你能告诉我怎么了吗?

    1 回复  |  直到 14 年前
        1
  •  0
  •   AndreasT    14 年前

    std::pair ! 我真丢脸!

    正确的getVal最后一行是:

            return boost::any_cast<T>(iter->second);
        }
    

    无论如何,谢谢。