答案是使用std::hash获取哈希值可将std::thread::id转为整数,再转字符串;或用ostringstream直接转字符串,后者更推荐用于日志输出。

在C++中,std::thread::id 是一个表示线程唯一标识的类型,它不直接提供转换为整数或字符串的方法。但可以通过 std::hash 来获取其哈希值,从而转换为整数,再进一步转为字符串。
由于 std::thread::id 不是整型,不能直接强转。标准做法是使用 std::hash<std::thread::id> 生成一个 size_t 类型的哈希值,这个值可以当作整数使用。
#include <thread>
#include <functional>
#include <iostream>
int main() {
std::thread t([]{
std::thread::id tid = std::this_thread::get_id();
std::hash<std::thread::id> hasher;
size_t id_as_integer = hasher(tid);
std::cout << "Thread ID as integer: " << id_as_integer << '\n';
});
t.join();
return 0;
}
基于上面的哈希值,可以将其转换为字符串。也可以直接将 std::thread::id 插入到 stringstream 中,因为其重载了输出操作符(operator<<)。
#include <thread>
#include <sstream>
#include <iostream>
#include <functional>
int main() {
std::thread t([]{
std::thread::id tid = std::this_thread::get_id();
// 方法一:通过哈希转字符串
std::hash<std::thread::id> hasher;
size_t hash_value = hasher(tid);
std::string id_str1 = std::to_string(hash_value);
// 方法二:通过 stringstream 输出(推荐)
std::ostringstream oss;
oss << tid;
std::string id_str2 = oss.str();
std::cout << "ID as string (hash): " << id_str1 << '\n';
std::cout << "ID as string (stream): " << id_str2 << '\n';
});
t.join();
return 0;
}
说明: 方法二更通用,能保留系统对 thread::id 的原始表示形式,适合日志输出等场景;方法一得到的是哈希值,适合用于哈希表或比较用途。
立即学习“C++免费学习笔记(深入)”;
以上就是c++++怎么将std::thread::id转换为整数或字符串_c++ thread::id转换方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号