Boost logo

Boost :

From: Jody Hagins (jody-boost-011304_at_[hidden])
Date: 2005-03-23 17:20:54


On Wed, 23 Mar 2005 15:37:34 -0600
"Michael Goldshteyn" <mgoldshteyn_at_[hidden]> wrote:

> "Jody Hagins" <jody-boost-011304_at_[hidden]> wrote in message
> news:20050323104956.15cd7630.jody-boost-011304_at_atdesk.com...
> > On Wed, 23 Mar 2005 09:01:51 -0600
> > "Michael Goldshteyn" <mgoldshteyn_at_[hidden]> wrote:
> >
> >> There is a bug in the sample code which cause me a lot of grief in
> >> understanding how boost::any functions, this morning. At:
> >>
> >> http://www.boost.org/doc/html/any/s02.html
> >>
> >> The code:
> >> ---
> >> bool is_string(const boost::any & operand)
> >> {
> >> return any_cast<std::string>(&operand);
> >> }
> >>
> >> should read:
> >>
> >> bool is_string(const boost::any & operand)
> >> {
> >> return any_cast<std::string *>(&operand);
> >> }
> >> ---
> >>
> >> Notice the addition of the asterisk.
> >
> >
> >
> > The original example looks fine to me. Why do you think it is
> > incorrect?
>
> The original example casts from an any pointer to an std::string,
> using any_cast, and returns the result implicitly cast to a boolean.
> So:
>
> 1. What does it mean to cast from an any pointer to an std::string,
> using any_cast?

In the referenced example,
any_cast<std::string>(&operand);
will return a std::string const * if the object inside the any is a
std::string, and 0 otherwise. For example...

#include <boost/any.hpp>
#include <string>
#include <cstring>
#include <cassert>

int main(int, char *[])
{
  // Stuff a ptr-to-const-char into any
  boost::any any = (char const *)"Hello";
  assert(boost::any_cast<char const *>(&any) != 0);
  assert(std::strcmp(
          *boost::any_cast<char const *>(&any),
          "Hello") == 0);

  assert(boost::any_cast<std::string>(&any) == 0);
  std::string hello = "hello";
  // Stuff a std::string into the any
  any = hello;
  assert(boost::any_cast<std::string>(&any) != 0);
  assert(*boost::any_cast<std::string>(&any) == hello);

  // Stuff a ptr-to-std::string into the any
  any = &hello;
  assert(boost::any_cast<std::string>(&any) == 0);
  assert(boost::any_cast<std::string*>(&any) != 0);
  assert(**boost::any_cast<std::string*>(&any) == hello);

  return 0;
}

> 2. What does it mean to implicitly convert a string, the value
> returned from any_cast<string> to a boolean?

Hmmm. Let's see if making the example more explicit will help. The
return type of boost::any_cast<std::string>(&any) is a "std::string
const *" so the original example is equivalent to...

bool is_string(const boost::any & operand)
{
  std::string const * ptr_to_string =
      boost::any_cast<std::string>(&operand);
  return ptr_to_string != 0;
}

Does that make sense, or just make it more confusing?!?


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk