tags:

views:

28

answers:

1

Hi, I am trying to implement a handy data repository or knowledge base for a little program of mine. I use a std::map of boost::any's to hold various pieces of information. For debugging and safety purposes, I have an extra safe accessor ''getVal()'' for the data.

A snippet says more than a thousand words:

EDIT: <<< Old snippet replaced by complete reproduction of error >>>

#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;
}

When I store a Something* in it, and try a
EDIT: as visible in the updated example code above, it doesn't need to be a pointer! Something* = kb->getVal it complains with: boost::exception_detail::clone_impl >' what(): boost::bad_any_cast: failed conversion using boost::any_cast

If I use KnowledgeBase::operator[] it works. Can you tell me what is wrong?

A: 

Oh short_n_crisp_exclamatory_word,{!}

I completely forgot that the iterator points to a std::pair ! Shame on me!

Sorry for bothering.

The correct last line of getVal is:

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

Thx, anyway.

AndreasT