boost/any.hpp (version 1.55) defines (line 263)
template<typename ValueType>
inline const ValueType * any_cast(const any * operand) BOOST_NOEXCEPT
{
return any_cast<ValueType>(const_cast<any *>(operand));
}
However, using const_cast<>
, may result in undefined behaviour if the original object was not declared const
as in
class foo
{
boost::any value;
template<typename T>
foo(T const&x) noexcept : value(x) {}
template<typename T>
const T*ptr() const noexcept
{ return boost::any_cast(value); }
};
So, is boost kosher?
This is legal code, since any_cast
returns const-pointer and any_cast
, that receives pointer, does not change its argument.
UB by standard can be only in 1 situation if you use const_cast
:
n3376 5.2.11/7
[ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier may produce undefined behavior (7.1.6.1). — end note ]