If I have a variable or member of a known type is there a method that I can static cast to said type without expressly stating the type?
Thus ensuring that should the variable change type in the future a re-compilation will be all that's needed.
A very basic example would be:
int y = 5;
uint32_t x;
x = static_cast< TYPEOF( x ) >( foo );
Now if at some point in the future x needed to change to an int64_t say it would be nice if only the declaration of the variable needed changed and not all the static_cast lines, of which there may be many.
As a personal note, I am compiling with g++ 6 and thus I am able to use c++14 features, though an answer compatible with other versions may benefit others.
只需使用decltype
:
x = static_cast<decltype(x)>(y);
As stated in the comments above the solution is
int y = 5;
uint32_t x;
x = static_cast< decltype( x ) >( y );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.