Boost logo

Boost Users :

Subject: Re: [Boost-users] boost::any and const pointers
From: James C. Sutherland (James.Sutherland_at_[hidden])
Date: 2009-12-02 14:03:06


On Dec 2, 2009, at 11:24 AM, Dominique Devienne wrote:

> On Wed, Dec 2, 2009 at 10:55 AM, James C. Sutherland
> <James.Sutherland_at_[hidden]> wrote:
>> 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.
>> }
>>
>> 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 not possible AFAIK. The first compiles alright, but will fail
> at runtime because the boost::any was constructed using a const int*.
> By design all extractions are checked at runtime only, and the
> typeid()/std::type_info of what you put in and what you try to get it
> as must be the same. Given your code, you can't even do get<int>(p,
> "int"), because a const int was put in, not an int (see your set()
> impl), and typeid(int) != typeid(const int). --DD
>
Actually, this runs just fine (at least on my mac running g++ 4.2.1).

Also, the following compiles and runs fine:
        int m = get<int>(p,"int");
This is because you cannot force const semantics on a copy.

I came up with a way to get const references out (using boost::ref), but can't get const pointers guaranteed. I fear that you are right about this not being possible.


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