是否有标准整数类型,其大小为模板参数?

Rus*_*lan 5 c++ templates integer

假设我需要制作一个模板,其N长度恰好为位,其中N是模板参数.我当然可以定义这样的东西

#include <cstdint>
template<int N>
struct sized_uint {};
template<> struct sized_uint<8> { typedef uint8_t type; };
template<> struct sized_uint<16> { typedef uint16_t type; };
template<> struct sized_uint<32> { typedef uint32_t type; };
template<> struct sized_uint<64> { typedef uint64_t type; };
Run Code Online (Sandbox Code Playgroud)

然后在我的模板中使用它,例如一个函数:

template<int N> void myfunc(typename sized_uint<N>::type);
Run Code Online (Sandbox Code Playgroud)

但是sized_uint在任何版本的C++中是否有像上面定义的标准类型?

Tar*_*ama 7

没有类似的标准类型.但是,有boost :: int_t,如果您可以接受boost依赖,它将执行您想要的操作.请注意,语义略有不同,因为boost::int_t它将为您提供至少具有多个位的最小整数类型,而不是那么多.