2017-06-16 11 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 के बारे में कभी नहीं जानता था। बहुत बहुत धन्यवाद। –

संबंधित मुद्दे