gpt4 book ai didi

c++ - 为什么 bernoulli_distribution::param_type 的构造函数是显式的?

转载 作者:行者123 更新时间:2023-11-30 01:51:00 25 4
gpt4 key购买 nike

在 §26.5.1.6/7 中说:

It is unspecified whether D::param_type is declared as a (nested) class or via a typedef. In this subclause 26.5, declarations of D::param_type are in the form of typedefs for convenience of exposition only.

这似乎表明 param_type 是实现定义的。特别是对于 GCC 和 Clang,以下不会编译:

std::bernoulli_distribution d(0.50);
d.param(0.25);

但对于 MSVC 2013,它确实如此。在 random.h 中查找 libstdc++,它表明 param_type 的构造函数被标记为显式:

struct param_type
{
typedef bernoulli_distribution distribution_type;

explicit
param_type(double __p = 0.5)
: _M_p(__p)
{
_GLIBCXX_DEBUG_ASSERT((_M_p >= 0.0) && (_M_p <= 1.0));
}

double
p() const
{ return _M_p; }

friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_p == __p2._M_p; }

private:
double _M_p;
};

因此不允许上面的代码编译。

他们选择显式构造函数的原因是什么?

最佳答案

阅读规范中的以下段落(在上面的引用之后); C++ § 26.5.1.6/9:

For each of the constructors of D taking arguments corresponding to parameters of the distribution, P shall have a corresponding constructor subject to the same requirements and taking arguments identical in number, type, and default values. Moreover, for each of the member functions of D that return values corresponding to parameters of the distribution, P shall have a corresponding member function with the identical name, type, and semantics.

在哪里;

  • P 是嵌入的param_type
  • D 是随机数分布。

并给定(§ 26.5.8.3.1);

explicit bernoulli_distribution(double p = 0.5);

可以说,bernoulli_distribution 的构造函数的要求是:

  • 从单个参数显式构建
  • 单个参数的类型是double
  • 该参数的默认参数为 0.5

因此,嵌入的 param_type 应该相同,因为它们将具有 “相同的要求”,如 § 26.5.1.6/9 所规定的。给它形式;

explicit param_type(double __p = 0.5) { /*...*/ }

尽管不可否认,我认为这在措辞上可能最初不是很清楚。我怀疑 libstdc++ 实现对规范有更准确的解释,而 MSVC 实现可能不正确。

更新

据报道,Microsoft 已经修复了此问题,请留意 VS 14 RTM 何时可用。

关于c++ - 为什么 bernoulli_distribution::param_type 的构造函数是显式的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26714209/

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