Boost类型擦除对象转回原类型触发boost::bad_any_cast问题求助
Why
boost::bad_any_cast Happens with Boost.TypeErasure any Ah, I see the issue here! You're mixing up two distinct Boost type erasure tools—boost::any and boost::type_erasure::any—and trying to use the wrong casting function with the latter. The boost::any_cast is designed exclusively for the general-purpose boost::any type, not the concept-driven any from Boost.TypeErasure. That's why you're hitting the runtime exception.
Here's the Fix
You need to use boost::type_erasure::any_cast instead, which is purpose-built for the concept-based any you're using. First, make sure to include the required header for this function:
#include <boost/type_erasure/any_cast.hpp>
Revised Working Code
Here's your code updated with the correct casting approach:
#include <boost/type_erasure/member.hpp> #include <boost/type_erasure/any.hpp> #include <boost/type_erasure/any_cast.hpp> // Critical missing header! #include <iostream> BOOST_TYPE_ERASURE_MEMBER((has_x), x, 0) namespace bte = boost::type_erasure; using xConcept = boost::mpl::vector<has_x <float(), bte::_self> , bte::copy_constructible<>, bte::relaxed>; using AnyXobject = bte::any<xConcept, bte::_self>; struct xThing{ float x(){ return 4.; } float y(){ return 5.; } }; int main(){ xThing i; AnyXobject xconc(i); std::cout << xconc.x() << std::endl; // This still works as expected // Use the correct any_cast from boost::type_erasure auto j = bte::any_cast<xThing>(xconc); std::cout << j.y() << std::endl; // Now you can access the original type's y() method // For safer, non-throwing conversion (returns nullptr on failure): if (auto j_ptr = bte::any_cast<xThing>(&xconc)) { std::cout << j_ptr->y() << std::endl; } return 0; }
Key Context to Remember
boost::anyis a simple, "catch-all" type erasure for any copyable type, whileboost::type_erasure::anyis a more flexible, concept-driven system that lets you define exactly which operations the erased type supports.- Their casting functions are not interchangeable—always match the
any_castto the type ofanyyou're using. - The non-throwing pointer version of
bte::any_castis great for cases where you're uncertain about the underlying type and want to avoid runtime exceptions.
内容的提问来源于stack exchange,提问作者the_toast
相关产品推荐
相关产品推荐

