模板-这可以做到吗
Templates - Can this be done?
本文关键字:模板 更新时间:2023-10-16
快速问题(真的是理论)。我有一个变量,它的类型根据值而变化,例如:
8, 16, 24, 32
我定义这一点,例如:
uint8_t = 10; // example
但是,目前我正在切换"数字"并重复代码,但以不同的方式声明整数值。正如你所知,这是很多浪费的代码,我想更有效地编码。
我想知道是否可以有一个根据值分配变量的模板?(如果有道理的话)。。
if value == 8
uint8_t = foo;
elseif value == 16
uint32_t
...
有什么想法或建议吗?谢谢:)
如此:
template <unsigned int N> struct IntN;
template <> struct IntN< 8> { typedef uint8_t type; };
template <> struct IntN<16> { typedef uint16_t type; };
template <> struct IntN<32> { typedef uint32_t type; };
template <> struct IntN<64> { typedef uint64_t type; };
IntN<8>::type x = 5;
模板参数必须是常量表达式。
相关文章:
- .cpp和.h文件中的模板专用化声明
- C++模板来检查友元函数的存在
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 如何在c++中为模板函数实例创建快捷方式
- 使用C++中的模板和运算符重载执行矩阵运算
- 有人能分解一下这个c++模板的语法吗
- 如何在c++17中制作一个模板包装器/装饰器
- 模板化建造师专业化
- 调用专用模板时出错"no matching function for call to [...]"
- 模板元程序查找相似的连续类型名称
- 如何在C++20中创建模板别名的推导指南
- 没有名称的C++模板参数
- 具有重复类型的C++可变模板
- 如何将enable-if与模板参数和参数包一起使用
- 没有用于初始化C++中的变量模板的匹配构造函数