【问题标题】:How to declare a class template in a structure and initialize later?如何在结构中声明类模板并稍后初始化?
【发布时间】:2019-02-04 17:16:52
【问题描述】:

我正在尝试对公差叠加进行建模。我制作了一个结构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 结构,因此我希望将分布与结构相关联,但我不确定它是否可能了。

【问题讨论】:

  • 您的错误信息与您的代码不匹配。请使用复制/粘贴,以便我们看到真实的东西。
  • @MarkRansom 这是我使用 gcc 4.8.1 版编译时遇到的错误g++ -std=gnu++11 main.cpp -o main.exe

标签: c++ c++11 random


【解决方案1】:

在这个阶段,对象已经构造好了,所以你可以这样做:

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)};

【讨论】:

  • 这行得通!不过,我仍然对为什么这样做感到困惑。 std::uniform_real_distribution&lt;double&gt; 是否调用构造函数?我以为您使用对象名称调用构造函数,即block.distribution(.240,.260)
  • 不,一旦构造了对象,你调用的是operator(),而不是构造函数。
  • 那么std::uniform_real_distribution&lt;double&gt;在做什么呢?
  • 创建一个新对象,然后我们将其复制到您的结构中。
猜你喜欢
  • 2018-08-13
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
相关资源
最近更新 更多