How to typecast std::thread::id
to string in C++? I am trying to typecast output generated by std::this_thread::get_id()
to a string or char array.
auto myid = this_thread::get_id();
stringstream ss;
ss << myid;
string mystring = ss.str();
Actually std::thread::id
is printable using ostream
(see this).
So you can do this:
#include <sstream>
std::ostringstream ss;
ss << std::this_thread::get_id();
std::string idstr = ss.str();
"converting" std::thread::id
to a std::string
just gives you some unique but otherwise useless text. Alternatively, you may "convert" it to a small integer number useful for easy identification by humans:
std::size_t index(const std::thread::id id)
{
static std::size_t nextindex = 0;
static std::mutex my_mutex;
static std::map<std::thread::id, std::size_t> ids;
std::lock_guard<std::mutex> lock(my_mutex);
if(ids.find(id) == ids.end())
ids[id] = nextindex++;
return ids[id];
}
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