如何在模板参数中设置模板类型的最大值和最小值

我一直在尝试创建一个模板函数(在C++中),该函数可以在模板参数内计算其数据类型(第一个模板参数)的最大值和最小值(因此我希望MIN和MAX变量能够是该函数中的第二个和第三个参数)。我正在尝试为任何数字类型创建通用的get_random_number()函数。

如果我对C++中的模板有误解,我深表歉意。我只是大学一年级的学生(在CS中),我在C++中所知道的几乎所有东西都是自学成才的。随时给我任何编码建议(例如样式,组织等)。

无论如何,这是我正在尝试的代码:

#include <type_traits>
#include <random>
#include <cmath>  // Pretty sure this is the header for pow()
using namespace std;  // I don't usually use this,but it shortens the code here

// Gets the size of a type in bits
template<typename Ty>
inline constexpr int b_sizeof()
{
    static_assert(is_arithmetic_v<Ty>,"Type must be numeric!");
    return sizeof(Ty) * 8;
}

// Gets a random number of a given type within [MIN,MAX]
template
<
    typename Ty,Ty MIN = is_unsigned_v<Ty> ? 0 : -pow(2,b_sizeof<Ty> - 1) + 1,Ty MAX = is_unsigned_v<Ty> ? pow(2,b_sizeof<Ty>) - 1 :
        pow(2,b_sizeof<Ty> - 1) - 1
>
inline constexpr Ty get_rand_num(Ty low = MIN,Ty high = MAX)
{
    static_assert(is_arithmetic_v<Ty>,"Type must be numeric!");
    if (is_integral_v<Ty>) uniform_int_distribution<Ty>(low,high);
    else uniform_real_distribution<Ty> dist(low,high);
    return dist(random_device());
}

我的问题是:这可以工作/编译吗?有没有更好的方法(如果可以,请说明)?

fangke45 回答:如何在模板参数中设置模板类型的最大值和最小值

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3120453.html

大家都在问