Question

It looks like calls to boost::any_cast<T>(any&) call some expensive typechecking to make sure that the cast is valid. Specifically, it calls performs the following test to make sure the cast is legal:

std::strcmp(operand->type().name(), typeid(ValueType).name()) == 0

If the cast is legal, the code then performs a static_cast.

This seems useful for debug mode, but is rather slow for production code. Is there any way to skip the strcmp?

Was it helpful?

Solution

boost::any includes a set of undocumented ValueType * unsafe_any_cast(any * operand) functions that do what you want for any* operands.

You could take the address of your reference to get what you want, or since Boost is open source, you could patch in a set of these function templates to take an any& operand.

Then just make a wrapper that uses the safe versions in debug builds and the unsafe versions in release builds. However, I'd make at least one further addition - the debug wrappers should catch the exception thrown for an invalid cast and invoke the debugger or crash the program so that when running in debug mode those invalid casts aren't handled in a way that hides the fact that the release build would have undefined behavior.

Also keep in mind that Boost reserves the right to remove the unsafe versions:

// Note: The "unsafe" versions of any_cast are not part of the
// public interface and may be removed at any time.

So if you decide to use these functions (or patch any.hpp to extend them), you're buying into some level of maintenance obligation that may or may not be acceptable depending on who your code might be deliverable to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top