开发者

Is there a way get an integer out of boost::any if you don't know if original type was signed or unsigned

开发者 https://www.devze.com 2023-04-11 20:08 出处:网络
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 boos

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::any does the simplest form of type-erasure, where the type must match exactly. You can write your own boost::any-like class that supports the additional features you want. I've previously demonstrated how this can be done.

Failing that, you can:

  1. Have two code paths, one for each sign. (Switch to signed path if any_cast<unsigned T> throws.)
  2. Try unsigned, and if that throws, try signed and cast, use a single code path.
  3. Just let the unsigned any_cast throw 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 want boost::variant instead, if you're expecting a certain list of types.

0

精彩评论

暂无评论...
验证码 换一张
取 消