【问题标题】:Choose smallest integer type based on a float根据浮点数选择最小整数类型
【发布时间】:2017-06-16 10:48:22
【问题描述】:

我正在尝试编写一个包含一个变量的类,该变量的类型将被选择为能够包含值的最小可能。

我的意思是:

class foo {
 "int type here" a;
}

我遇到了Automatically pick a variable type big enough to hold a specified number。 由于使用 boost 库的困难,我继续使用模板建议。

这会将代码变成:

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。有没有其他方法可以将变量(在编译期间应该可用)传递给类?

【问题讨论】:

    标签: c++ c++11 templates


    【解决方案1】:

    使用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, "!!");
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      相关资源
      最近更新 更多