I’m using boost::any in combination with boost::any_cast<> to write some framework code which should take a set of arguments, almost like a function call, and convert them into an array of boost::any types.
So far everything has been working great, except in places where it is hard to predict if the number the caller gives me is going to be signed or unsigned. A lot of code in our existing product (windows based) uses DWORD and BYTE data types for local variables so if one of those variables is used, I get unsigned type. However if a constant is hardcoded, the most likely it’ll be a simple number in which case it will be signed.
Since I can’t predict if I should do any_cast<int> or any_cast<unsigned int>, 50% of the time my code that reads the boost::any array will fail.
Does anyone know if there’s a way to just a number out of boost::any regardless if original type was signed or unsigned?
There isn’t a way;
boost::anydoes the simplest form of type-erasure, where the type must match exactly. You can write your ownboost::any-like class that supports the additional features you want. I’ve previously demonstrated how this can be done.Failing that, you can:
any_cast<unsigned T>throws.)any_castthrow if it’s signed, and force the user to cope.However, each of these isn’t really that good. Do you really need
boost::any? Perhaps you wantboost::variantinstead, if you’re expecting a certain list of types.