簡體   English   中英

C++ 寫入宏以查找 integer 類型給定另一個 integer 類型

[英]C++ Write Macro for finding an integer type given another integer type

我有一個 function 看起來像這樣:

template<class T, class E, class U = T> T function(T input1, E input2) {
    // implementation here
}

而不是上面的聲明,我希望U的默認值是一個以T為輸入的宏。 更具體地說,如果Tboost::multiprecision::cpp_int boost::multiprecision::cpp_int U我希望U的默認值為 integer ,對於固定精度T ,其精度是T的兩倍.

我知道第二部分可以通過以下方式完成:

U = boost::uint_t<2 * std::numeric_limits<T>::digits>::fast

如何檢查T是否為cpp_int (或 std 和 boost 中的任何其他任意精度 integer ),並將所有內容放在一個宏中?

編輯:

我發現可以通過以下方式測試任意精度:

std::numeric_limits<T>::is_bounded

我仍然不知道如何將這 2 個測試組合成 1 個宏。

如果T的雙倍大小大於int64_t ,一種方法可能是使用boost::multiprecision::cpp_int

主意:

#include <boost/multiprecision/cpp_int.hpp>

#include <cstddef>
#include <type_traits>

// type trait to get an int of the requested size
template<size_t S>
struct int_size {
    using type = std::conditional_t<S==1, int8_t,
                     std::conditional_t<S==2, int16_t,
                         std::conditional_t<S==4, int32_t,
                             std::conditional_t<S==8, int64_t,
                                                boost::multiprecision::cpp_int>>>>;
};

template<size_t S>
using int_size_t = int_size<S>::type;

然后使U的大小加倍Tboost::multiprecision::cpp_int如果它大於int64_t

template<class T, class E, class U = int_size_t<sizeof(T) * 2>> 
T function(T input1, E input2) {
    // implementation here
}

演示

使用宏定義了一個自定義的 boost multiprecision int,並將 function 后端隱藏在另一個檢查類型的 function 后面。 U 是無效的,因此用戶可以選擇自定義它。 如果 T 是固定精度,則 function 調用宏,否則將 cpp_int 作為模板參數傳遞。 自定義 boost int 的類型推導是在編譯時完成的,if 語句也可能在編譯時進行評估。

#include <limits>
#include <type_traits>

#ifndef BOOST_UINT
#define BOOST_UINT(bit_count) boost::multiprecision::number<boost::multiprecision::cpp_int_backend<bit_count, bit_count, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>
#endif

template<class T, class E, class U = void> T function(T input1, E input2) {
    if(std::is_same<U, void>::value) {
        if(std::numeric_limits<T>::is_bounded) {
            return function_backend<T, E, BOOST_UINT(2 * std::numeric_limits<T>::digits)>(input1, input2);
        } else {
            return function_backend<T, E, cpp_int>(input1, input2);
        }
    } else {
        return function_backend<T, E, U>(input, input2);
    }
}

template<class T, class E, class U> T function_backend(T input1, E input2);

暫無
暫無

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

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