Boost logo

Boost Users :

Subject: [Boost-users] Fwd: any_cast and added low-level const -> throws
From: nice sw123 (nicesw123_at_[hidden])
Date: 2015-09-23 16:25:06


On Wed, Sep 23, 2015 at 9:55 PM, nice sw123 wrote:
> Hi,
>
> can anyone explain why an any_cast that adds a low-level const throws??
>
> Example:
> char str[] = "a2";
> boost::any ay(str);
> boost::any_cast<const char*>(ay); // throws, since a const is added!!!
>
> The only way to do this (without throwing), seems to be:
> boost::any_cast<char*>(ay);
>
> But why this mild "design deficiency"??

If I change this code
https://github.com/boostorg/any/blob/ed7cac4ee207b125aa25144f2674f9550def2232/include/boost/any.hpp#L243

to

    template<typename ValueType>
    ValueType * any_cast(any * operand) BOOST_NOEXCEPT
    {
      return &static_cast<any::holder<BOOST_DEDUCED_TYPENAME
remove_cv<ValueType>::type> *>(operand->content)->held;
      /*
            return operand && operand->type() ==
boost::typeindex::type_id<ValueType>()
            ? &static_cast<any::holder<BOOST_DEDUCED_TYPENAME
remove_cv<ValueType>::type> *>(operand->content)->held
             : 0;
      */
    }

then I can do what I want!! Then adding low-level const is fine!!!
(Probably I remove some safety, for truely illegal casts; but at least
I have proof that it would be possible to add low-level const!
Does any C++ guru have suggestions on integrating typesafety, but
still allowing low-level const to be added? Thanks
)

With the above changes, the following now actually works:

same code as in first post
///////
#include <iostream>
#include <algorithm>
#include <boost/any.hpp>

int main()
{
  char str[] = "a1";

  boost::any ay(str);
  std::cout << "1 -- " << boost::any_cast<char *>(ay) << std::endl;

  strcpy(str, "a2");
  std::cout << "2 -- " << boost::any_cast<const char*>(ay) << std::endl;
  // -> no throws !!!

  strcpy(str, "a3");
  std::cout << "3 -- " << *boost::any_cast<char *>(&ay) << std::endl;

  strcpy(str, "a4");
  std::cout << "4 -- " << *boost::any_cast<const char *>(&ay) << std::endl;
  // -> no segault !!!

  char str2[] = "str2";
  std::cout << "str2 -- " << static_cast<const char *>(str2) << std::endl;

  return 0;
}
///////


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