如何在结构中声明类模板并在以后初始化

How to declare a class template in a structure and initialize later?

本文关键字:初始化 结构 声明      更新时间:2023-10-16

我正在尝试对公差堆叠进行建模。我做了一个结构Layer,它保持公差范围的下限(tol[0](和上限(tol[1](。我想在 tol[0]tol[1] 之间生成一个随机值并将其分配给val.

我的实现在结构中声明了uniform_real_distribution类模板并在main()中对其进行初始化,但是我在编译过程中遇到错误,使我认为我不能以这种方式使用类模板。

#include <random>
struct Layer {
    double tol[2];
    double val;
    std::string name;
    std::uniform_real_distribution<double> distribution;
};
int main() 
{
    Layer block;
    block.tol[0] = .240;
    block.tol[1] = .260;
    std::default_random_engine generator;
    block.distribution(block.tol[0],block.tol[1]);
    block.val = block.distribution(generator);
    return 0;
}

我从 g++ 收到以下错误:

error: no match for call to '(std::uniform_real_distribution<double>) (double&, double&)'
    block.distribution(block.tol[0],block.tol1[]);
                                                ^

我创建了很多Layer结构,所以我希望将发行版与结构相关联,但我不确定它是否可能。

在此阶段,对象已经构造完成,因此您可以执行以下操作:

block.distribution = std::uniform_real_distribution<double>(block.tol[0],block.tol[1]);

您也可以直接初始化结构:

Layer block{{.240,.260}, 0, "", std::uniform_real_distribution<double>(.240, .260)};