Boost logo

Boost Users :

Subject: [Boost-users] any_cast and added low-level const -> throws
From: nice sw123 (nicesw123_at_[hidden])
Date: 2015-09-23 15:55:50


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"??
I call it "design deficiency", since the following is legal and works:

  char str2[] = "str2";
  static_cast<const char *>(str2);

So we should be able to add a low-level const, to make something
read-only, right.

Thanks for comments and explanations.
n.

Here's some test-code:

///////
#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");
  /* throws!! */ //std::cout << "2 -- " << boost::any_cast<const
char*>(ay) << std::endl;

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

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

  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