2017-06-16 48 views
14

我試圖寫一個類,其中包括一個變量,其類型將選擇到儘可能小的能包含值最小整數類型。選擇基於一個浮動

我的意思是:

class foo { 
"int type here" a; 
} 

我遇到Automatically pick a variable type big enough to hold a specified number來了。 由於使用升壓庫困難,我繼續使用的模板建議。

那會使代碼爲:

template<unsigned long long T> 
class foo { 
SelectInteger<T>::type a; 
} 

不過,我的問題源於一個事實,即變量的大小是一個浮點變量和整數相乘的結果。因此,我希望能夠做的是:

template<unsigned long long T, double E> 
class foo { 
SelectInteger<T*E>::type a; 
} 

但由於模板不與浮點變量(見here)工作,我不能在一個模板傳E。有一些其他的方式,我可以傳遞一個變量(編譯過程中應備有)的類?

回答

8

有關使用constexpr功能是什麼?

我的意思是......什麼如下

template <unsigned long long> 
struct SelectInteger 
{ using type = int; }; 

template <> 
struct SelectInteger<0U> 
{ using type = short; }; 

constexpr unsigned long long getSize (unsigned long long ull, double d) 
{ return ull*d; } 

template <unsigned long long T> 
struct foo 
{ typename SelectInteger<T>::type a; }; 

int main() 
{ 
    static_assert(std::is_same<short, 
        decltype(foo<getSize(1ULL, 0.0)>::a)>::value, "!"); 
    static_assert(std::is_same<int, 
        decltype(foo<getSize(1ULL, 1.0)>::a)>::value, "!!"); 
} 
+0

從來不知道constexpr。非常感謝。 –