Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert std::thread::id to std::string

Tags:

c++

How can I convert std::thread::id which is a class into a std::string? If I print std::thread::id using std::cout, I could see an integer getting printed, and this is possible because of << operator overloading.

#include <iostream>
#include <thread>

int main() {
    std::cout << std::to_string(std::this_thread::get_id()) << std::endl;
}
like image 825
Harry Avatar asked Feb 01 '26 02:02

Harry


1 Answers

With C++23, there is formatting support for thread::id, so you can do this:

#include <format>
#include <iostream>
#include <thread>

int main()
{
    std::string s = std::format("{}", std::this_thread::get_id());
    std::cout << s << "\n";
}
like image 131
abcdefg Avatar answered Feb 02 '26 17:02

abcdefg