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

如何在模板参数中编译时确定类型(替代三元运算符写法)

简洁实现方案

在C11及以后的标准中,你可以直接借助标准库的std::conditional(C14起可用更简洁的std::conditional_t)来实现这种模板参数的类型选择,完全不需要自定义特化的辅助结构体:

C++14及以上版本写法:

#include <type_traits>

template <bool is_true>
class A {
    B<std::conditional_t<is_true, int, float>> var;
};

C++11版本写法:

#include <type_traits>

template <bool is_true>
class A {
    B<typename std::conditional<is_true, int, float>::type> var;
};

这个方案的优势:

  • 直接复用标准库原生组件,无需额外定义辅助结构
  • 语法逻辑和你期望的三元运算符完全一致,可读性强
  • 兼容性覆盖绝大多数现代C++编译环境

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:35:59