You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将std::thread::id类对象转换为std::string字符串?

如何将std::thread::id转换为std::string?

你提到用std::cout能直接打印std::thread::id,确实是因为标准库已经为这个类重载了<<运算符,但直接用std::to_string会编译失败——因为std::to_string只支持算术类型(比如int、long、double等),而std::thread::id是一个类类型,并不符合参数要求。

下面是几种可行的转换方法:

方法1:使用std::ostringstream(C++11及以上)

借助已有的<<重载,把线程ID输出到字符串流,再提取成std::string:

#include <iostream>
#include <thread>
#include <sstream>
#include <string>

int main() {
    std::thread::id tid = std::this_thread::get_id();
    std::ostringstream oss;
    oss << tid;
    std::string tid_str = oss.str();
    std::cout << tid_str << std::endl;
    return 0;
}

方法2:使用std::format(C++20及以上)

C++20引入的std::format可以更简洁地完成转换:

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

int main() {
    std::string tid_str = std::format("{}", std::this_thread::get_id());
    std::cout << tid_str << std::endl;
    return 0;
}

你提供的原代码会编译报错,核心原因就是std::to_string无法处理std::thread::id这种类类型,替换成上面的方法就能正常运行了。

内容的提问来源于stack exchange,提问作者Harry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 01:42:33