Boost logo

Boost Users :

Subject: [Boost-users] boost::any and const pointers
From: James C. Sutherland (James.Sutherland_at_[hidden])
Date: 2009-12-02 11:55:19

I have a
that I would like to control access to so that if a pointer is put in the map, only a const pointer can be extracted. The following simple code illustrates the situation.

//-------------------- <snip> --------------------------
typedef std::map<std::string,boost::any> Properties;

template<typename T>
set( Properties& p, const std::string name, const T t )
  p[name] = t;

template<typename T>
const T
get( const Properties& p, const std::string name )
  const Properties::const_iterator iprop=p.find(name);
    const T t = boost::any_cast<const T>(iprop->second);
    return t;
  catch(const boost::bad_any_cast &){
    throw std::runtime_error("bad cast");

int main()
  Properties p;
  int i=1;

  int* j = get<int*>(p,"int*"); // I don't want this to compile
  const int* k = get<int*>(p,"int*"); // I want this to compile fine.
//-------------------- </snip> -------------------------

Currently this whole code compiles without trouble, but I don't want to allow a non-const pointer to be extracted. Any ideas of how to accomplish this?

Thanks for any tips!

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at