2015-07-21 41 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)。 –

相關問題