|
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
map<string,any>
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>
void
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);
try{
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;
set(p,"int",i);
set(p,"int*",&i);
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 hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net