簡體   English   中英

用模板替換constexpr(用於在編譯時計算常量)嗎?

[英]Replace constexpr (used to calculate constant at compile time) with template?

我使用constexpr關鍵字來計算能夠在編譯時存儲在float或double中的最大整數值(n是尾數的位數,val最初是1.0):

constexpr double calc_max_float(int n, double val)
{
    return (n == 0) ? (val) : calc_max_float(n - 1, 2.0*val);
}

生成此值以供以下模板使用:

template <bool, class L, class R>
struct IF  // primary template
{
    typedef R type;
};

template <class L, class R>
struct IF<true, L, R> // partial specialization
{
    typedef L type;
};

template<class float_type>
inline float_type extract_float()
{
    return (extract_integer<typename IF<sizeof(float_type) == 4,
                                        uint32_t,
                                        uint64_t
                                       >::type
                           >() >> (8*sizeof(float_type) - std::numeric_limits<float_type>::digits))*(1./calc_max_float(std::numeric_limits<float_type>::digits, 1.0));
}

該模板生成兩個函數,等效於:

inline float extract_single()
{
    return (extract_integer<uint32_t>() >> 9) * (1./(8388608.0));
}
inline double extract_double()
{
    return (extract_integer<uint64_t>() >> 12) * (1./(67108864.0*67108864.0));
}

在GCC中一切都很好,但是我也希望能夠使用VC11 / 12進行編譯。 關於如何替換constexpr calc_max_float(int n, double val)任何想法?

編輯:

為了清楚起見,我正在尋找一種在編譯時使用模板來計算常量pow(2,x)的方法。 甚至在正確方向上的一點也很好。

至於用法示例,我有一個函數extract_integer(min類型,類型范圍),該函數可用於任何有符號或無符號類型。 我正在嘗試創建一個函數extract_float(),該函數返回float或double類型的值[0,1)。

我想我正在尋找類似的東西:

template <const unsigned  N, const uint64_t val>
inline uint64_t calc_max_float()
{
    return calc_max_float<N - 1,2*val>();
}

template <const uint64_t val>
inline double calc_max_float<0, val>()
{
    return (double) val;
}

但是,不允許對功能進行部分專業化嗎? 而當我們在這樣做的時候,為什么會不會像

template <const unsigned  N, const uint64_t val>
inline uint64_t calc_max_float()
{
    return (N != 0) ? calc_max_float<N - 1,2*val>() : val;
}

工作?

#include <iostream>

template <unsigned  N>
inline double calc_max_float(double val)
{
    return calc_max_float<N - 1>(2.0 * val);
}

template <>
inline double calc_max_float<0>(double val)
{
    return val;
}

int main() {
    // 2 ^ 3
    std::cout << calc_max_float<3>(1) << std::endl;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM