如何在模板参数中编译时确定类型(替代三元运算符写法)
简洁实现方案
在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
相关产品推荐
相关产品推荐

