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

标签 c++ templates

<分区>

我有一个返回随机数的函数,并针对带有概念的整数和 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

这可能吗?

最佳答案

不,这不是 Haskell,C++ 不能根据周围的上下文推断表达式的类型。

你可以做的是根据初始化推断变量的类型(这不是赋值):

auto i = rand<int>(r,0,2);  // int i
auto s = rand<short>(r,0,3); // short s
auto d = rand<double>(r,0,6); // double d
auto dd = rand<double>(r,0,6); // double dd

前提是 rand 返回正确的类型。

关于c++ - 根据赋值实例化模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73823881/

相关文章:

c++ - 有没有办法在 C++ 中显示/打印变量/成员的属性

c++ - 这个表达式 a = a + b - ( b = a );由于 C++ 中的序列点而给出错误的输出?

c++ - 使用 SFML 移动对象

c++ - 为什么 clang 无法使用默认的 integer_sequence 实例化嵌套的可变参数模板?

java - 安卓 OpenCV : color detection giving weird result

c++ - inpaint() 没有产生预期的结果。为什么?

c++ - 使用 SFINAE 禁用模板类成员函数

c++ - 为什么从基模板类继承并将两个类文件放在单独的头文件中时会出现重定义错误?

头文件中的c++模板单例静态指针初始化

c++ - 为什么显式模板实例化会在存在外线虚拟时导致 weak-template-vtables 警告?