Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing an unsigned integer in std::any

Tags:

c++

stl

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.

like image 973
Bartosz Golaszewski Avatar asked Nov 02 '25 01:11

Bartosz Golaszewski


1 Answers

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++ into a dynamically typed 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.

like image 64
bolov Avatar answered Nov 03 '25 16:11

bolov