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(ay); // throws, since a const is added!!!
The only way to do this (without throwing), seems to be:
boost::any_cast(ay);
But why this mild "design deficiency"??
If I change this code
https://github.com/boostorg/any/blob/ed7cac4ee207b125aa25144f2674f9550def223...
to
template<typename ValueType>
ValueType * any_cast(any * operand) BOOST_NOEXCEPT
{
return &static_cast *>(operand->content)->held;
/*
return operand && operand->type() ==
boost::typeindex::type_id<ValueType>()
? &static_cast *>(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
int main()
{
char str[] = "a1";
boost::any ay(str);
std::cout << "1 -- " << boost::any_cast(ay) << std::endl;
strcpy(str, "a2");
std::cout << "2 -- " << boost::any_cast(ay) << std::endl;
// -> no throws !!!
strcpy(str, "a3");
std::cout << "3 -- " << *boost::any_cast(&ay) << std::endl;
strcpy(str, "a4");
std::cout << "4 -- " << *boost::any_cast(&ay) << std::endl;
// -> no segault !!!
char str2[] = "str2";
std::cout << "str2 -- " << static_cast(str2) << std::endl;
return 0;
}
///////