gpt4 book ai didi

c++ - 根据赋值实例化模板函数

转载 作者:行者123 更新时间:2023-12-05 05:33:31 26 4
gpt4 key购买 nike

<分区>

我有一个返回随机数的函数,并针对带有概念的整数和 float 进行模板化。

template <typename T>
struct distribution_selector;

template<std::integral I>
struct distribution_selector<I> {
using type = std::uniform_int_distribution<I>;
};

template<std::floating_point F>
struct distribution_selector<F> {
using type = std::uniform_real_distribution<F>;
};

struct random {
std::mt19937 engine;
};

template<typename T>
requires std::integral<T> || std::floating_point<T>
constexpr inline decltype(auto) rand(random& r, T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max()) {
using distribution = distribution_selector<T>::type;
return distribution(min, max)(r.engine);

}

为了便于使用,我想省略 T 的模板参数,具体取决于我将函数结果分配给什么:

int main() {
using namespace r;
random r;
int i = rand(r,0,2); // will call rand<int>, correct
short s = rand(r,0,3); // will call rand<int>, but I want rand<short>
double d = rand(r,0,6); // will also call rand<int>, but i want rand<double>
double dd = rand<double>(r,0,6); // will of course call rand<double>
return s;
}

Demo

这可能吗?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com