How could I convert any type to a string in C++?
std::string val;
template<typename T> std::string AnyToString(T val) {
return (std::string)val;
}
template<typename T> void SetVal(T val) {
this->val = AnyToString(val);
}
int main() {
SetVal(10);
return 0;
}
Above code gives me an error, cannot convert int to string. reinterpret_cast<>, static_cast<>, etc. don't work either.
First off, some style issue: (std::string)val is a C-style cast, something that is frowned upon in the C++ community. There are several disadvantages, including lack of type safety and that you cannot find it in a large amount of C++ code. C++ introduces different types of casts for different goals: static_cast<>,dynamic_cast<>, reinterpret_cast<> and const_cast<>.
However, you shouldn't try to just "cast" an int to a string, that doesn't work. Please use std::to_string: http://en.cppreference.com/w/cpp/string/basic_string/to_string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With