$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
Subject: Re: [Boost-users] boost::any and const pointers
From: James C. Sutherland (James.Sutherland_at_[hidden])
Date: 2009-12-02 16:29:18
On Dec 2, 2009, at 2:19 PM, Steven Watanabe wrote:
> AMDG
> 
> James C. Sutherland wrote:
>> 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?
>>  
> 
> template<typename T>
> const typename boost::remove_pointer<T>::type*
> get(const Properties& p, const std::string& name);
> 
> In Christ,
> Steven Watanabe
> 
Thank you!
That works great for pointers, but now not for POD, e.g.,
        const int m = get<int>(p,"int");
Any ideas of how to get this to work with POD and pointers?