<分区>
我有一个返回随机数的函数,并针对带有概念的整数和 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;
}
这可能吗?