模板-这可以做到吗

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;

模板参数必须是常量表达式。