2012-05-23 67 views
6

我很想學習一點關於模板元編程的知識。在下面的代碼中,我試圖找到一個無符號整數類型,它足夠大,以便在編譯時指定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

這應該解決我的實際需求和求知慾。

+0

爲什麼不使用stdint.h? – mfontanini

+0

@mfontanini你能否詳細說明一下? – TractorPulledPork

回答

2

您的問題是_type::type評估爲std::conditional<...>::type,而不是FindIntegralType2<...>::type。將其更改爲typedef typename _type::type::type type;(太多type x_X)。這應該可以解決你的問題。

+0

這是正確的。謝謝! – TractorPulledPork