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

C++17如何优雅地将长类型名传递给模板参数?

最优实现方案

你想要的类似typeof的语法在标准C中可以通过decltype关键字直接实现,C11及以上版本均支持该特性,完全符合你的需求,改写后代码如下:

void foo(){
    auto root = m_tablebase.find(m_root_hash);
    // 直接通过decltype获取root的类型作为queue的模板参数
    std::queue<decltype(root)> to_visit;
    to_visit.push(root);
}

decltype的作用是获取表达式的静态编译期类型,不需要你手动拼写完整的迭代器类型,也不需要额外定义typedef别名,是最简洁的实现方式。同时这种写法也规避了你原代码中直接引用libc++内部命名空间std::__1的问题,跨编译器兼容性更好。

可复用类型的优化方案

如果该迭代器类型在代码中多处使用,可以在结构体内部提前用using定义类型别名(现代C++更推荐用using代替typedef做类型别名声明,可读性更强):

struct OpeningTablebase
{
  // 提前定义容器和迭代器别名
  using Tablebase = std::unordered_map<z_hash_t, std::shared_ptr<std::vector<MoveEdge>>>;
  using Iter = Tablebase::iterator;

  Tablebase m_tablebase;
};

void foo(){
    auto root = m_tablebase.find(m_root_hash);
    std::queue<OpeningTablebase::Iter> to_visit;
    to_visit.push(root);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:24:00