Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert any type to string c++

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.

like image 270
Teytix Avatar asked Feb 18 '26 10:02

Teytix


1 Answers

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

like image 166
Klaas van Gend Avatar answered Feb 20 '26 00:02

Klaas van Gend



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!