Boost logo

Boost Users :

Subject: Re: [Boost-users] Determine Parent Class from boost::any
From: Ovanes Markarian (om_boost_at_[hidden])
Date: 2009-11-23 11:58:35


Hi!
what do you mean by parent? boost::any does not derive from any other class.
Just a note, using that version of cast:

       boost::any_cast<a*>(&any);
or
       boost::any_cast<a const*>(&any);

will not throw, but return a null pointer if any does not contain the
expected type. Consider using boost::variant, which supports visitor-pattern
for dispatching.

Best Regards,
Ovanes

On Mon, Nov 23, 2009 at 5:18 PM, Yan Cheng Cheok <yccheok_at_[hidden]> wrote:

>
> May I know is there any way to determine parent class from boost::any?
>
> #include <iostream>
> #include <boost/any.hpp>
>
> class a {
> public:
> virtual ~a() {}
> };
>
> class b : public a {
> };
>
> bool is_class_a(const boost::any& any)
> {
> return boost::any_cast<a>(&any) != 0;
> }
>
> bool is_class_a_v2(const boost::any& any)
> {
> try
> {
> boost::any_cast<a>(any);
> return true;
> }
> catch(const boost::bad_any_cast &)
> {
> return false;
> }
> }
>
> int main()
> {
> std::cout<< is_class_a(b())<< std::endl; // return 0. but i wish to
> return 1.
> std::cout<< is_class_a(a())<< std::endl; // return 1.
>
> std::cout<< is_class_a_v2(b())<< std::endl; // return 0. but i wish to
> return 1.
> std::cout<< is_class_a_v2(a())<< std::endl; // return 1.
> }
>
>
>
>
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>



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