Reputation: 109
In C#, there is a class with static methods for type conversions:Convert.ToUInt16()
. Is there a C++ equivalent of these methods. I know a few, like to_string from string.h, but it would be better if all of these type conversions were in one place.
Upvotes: 1
Views: 232
Reputation: 10962
Pre c++17 you can just do:
short int i;
std::istringstream iss{int_string};
iss >> i;
With c++17 you may also use std::from_chars
- the preferred method. See also this answer.
Upvotes: 3
Reputation: 62576
if all of these type conversions were in one place
Conversions to or from std::string
are in namespace std
, whilst conversions between arithmetic types are casts.
std::cout << std::to_string(1.2)
int i;
auto num = "1"s;
std::from_chars(num.begin(), num.end(), i);
std::cout << i;
std::cout << static_cast<std::uint16_t>(1.2);
For conversions of user-defined-types, rather than defining an interface like IConvertible
, C++ allows you to define operator int
et.al. in your class.
Upvotes: 4