我很想學習一點關於模板元編程的知識。在下面的代碼中,我試圖找到一個無符號整數類型,它足夠大,以便在編譯時指定N位,並使用一些模板遞歸。C++遞歸模板類型推理
template <typename T>
struct NextIntegralType
{
};
template <>
struct NextIntegralType<void>
{
typedef unsigned char type;
};
template <>
struct NextIntegralType<unsigned char>
{
typedef unsigned short type;
};
...More type 'iteration' here...
template<size_t BITS, typename T>
struct FindIntegralType2
{
typedef std::conditional<BITS <= sizeof(typename T::type)*8, T, FindIntegralType2<BITS, NextIntegralType<typename T::type>>> _type;
typedef typename _type::type type;
};
template<size_t BITS>
struct FindIntegralType
{
typedef typename FindIntegralType2<BITS, NextIntegralType<void>>::type type;
};
當我聲明一個變量並分配一個整數值吧...
FindIntegralType<15>::type test(4000);
我得到如下:
error: no matching function for call to ‘FindIntegralType2<15u, NextIntegralType<unsigned char> >::FindIntegralType2(int)’
note: candidates are:
note: constexpr FindIntegralType2<15u, NextIntegralType<unsigned char> >::FindIntegralType2()
note: candidate expects 0 arguments, 1 provided
note: constexpr FindIntegralType2<15u, NextIntegralType<unsigned char> >::FindIntegralType2(const FindIntegralType2<15u, NextIntegralType<unsigned char> >&)
note: no known conversion for argument 1 from ‘int’ to ‘const FindIntegralType2<15u, NextIntegralType<unsigned char> >&’
好像我的遞歸是不是'平倉」。任何人都可以將我指向正確的方向嗎?我使用GCC 4.6。
編輯:
我發現後,我錯過了前:
Automatically pick a variable type big enough to hold a specified number
指向升壓答案(他們總是有):
boost_integer
這應該解決我的實際需求和求知慾。
爲什麼不使用stdint.h? – mfontanini
@mfontanini你能否詳細說明一下? – TractorPulledPork