2017-06-16 49 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。非常感谢。 –