2015-07-21 45 views
4

假设我需要创建一个长度为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; }; 

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

template<int N> void myfunc(typename sized_uint<N>::type); 

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

+1

看看这个http://stackoverflow.com/questions/31334291/select-an-integer-type-based-on-template-integer-parameter/31334843#31334843,和我相当辉煌的答案; =) 。你可以这样做。 – Bathsheba

回答

7

没有这样的标准类型。但是,有boost::int_t,如果您可以接受boost依赖关系,它将执行您所需的操作。请注意,语义略有不同,因为boost::int_t会给你最小整数类型,至少至少那么多位,而不是那么多。

+0

由于其2016年的日期和Boost.Integer的引用,[P0381R1](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0381r1.html)支持此正确性回答。然而,我想用这种类型的两个东西可以在''中找到:[std :: make_unsigned](http://en.cppreference.com/w/cpp/types/make_unsigned) ,[std :: underlying_type](http://en.cppreference.com/w/cpp/types/underlying_type)。 –

相关问题