Home > Net >  Storing an unsigned integer in std::any
Storing an unsigned integer in std::any

Time:02-23

Can I make ::std::any hold an unsigned integer? Something like:

::std::any a = 4;
unsigned int x = ::std::any_cast<unsigned int>(a);

results in an ::std::bad_any_cast exception because a actually holds a signed integer.

CodePudding user response:

Yes, just put an unsigned integer in it:

::std::any a = 4u;
// or
::std::any a = static_cast<unsigned>(4);

https://godbolt.org/z/vzrYnKKe9


I have to caution you. std::any is not a magical tool to convert C in a dynamically type language like python or javascript. Its use cases are very narrow and specific. It's not really meant to be used in user code as a "catch all" type. It's meant as a type safe alternative to void * in low level library code.

CodePudding user response:

It's because 4 is an int by default.

You need to specify unsigned when you fill the std::any variable:

std::any a = 4u;
unsigned int x = std::any_cast<unsigned int>(a);
  • Related