快速问题(理论真的).我有一个变量,其类型根据值交替,例如:
8, 16, 24, 32
Run Code Online (Sandbox Code Playgroud)
我通过这样做来定义它,例如:
uint8_t = 10; // example
Run Code Online (Sandbox Code Playgroud)
但是,在我切换"数字"并重复代码但是以不同方式声明整数值的那一刻.正如您所知,这是一个浪费很多的代码,我想更有效地编码.
我想知道是否有可能根据值分配变量的模板?(如果这是有道理的)..
if value == 8
uint8_t = foo;
elseif value == 16
uint32_t
...
Run Code Online (Sandbox Code Playgroud)
任何想法或建议?谢谢 :)
像这样:
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;
Run Code Online (Sandbox Code Playgroud)
模板参数必须是常量表达式.