我有一個看起來像這樣的函式:
template<class T, class E, class U = T> T function(T input1, E input2) {
// implementation here
}
而不是上面的宣告,我希望默認為U一個接受T輸入的宏。更具體地說,我希望 for 的默認值U是boost::multiprecision::cpp_intif Tis boost::multiprecision::cpp_int,我希望 for 的默認值U是一個整數,其精度是Tfor fixed precision 的兩倍T。
我知道第二部分可以通過以下方式完成:
U = boost::uint_t<2 * std::numeric_limits<T>::digits>::fast
我如何檢查是否T是一個cpp_int(或 std 和 boost 中的任何其他任意精度整數),并將所有內容放在一個宏中?
編輯:
我發現可以通過以下方式測驗任意精度:
std::numeric_limits<T>::is_bounded
我仍然不知道如何將這 2 個測驗組合成 1 個宏。
uj5u.com熱心網友回復:
一種方法是使用boost::multiprecision::cpp_int如果 的雙倍大小T大于int64_t.
主意:
#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_intint64_t
template<class T, class E, class U = int_size_t<sizeof(T) * 2>>
T function(T input1, E input2) {
// implementation here
}
演示
uj5u.com熱心網友回復:
使用宏定義了一個自定義的 boost 多精度 int,并將函式后端隱藏在另一個檢查型別的函式后面。U 是無效的,以便用戶可以選擇自定義它。如果 T 是固定精度,則函式呼叫宏,否則將 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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/388703.html
下一篇:將模板模板引數限制為兩種型別之一
