【问题标题】:Using numeric_limits to default parameter values对默认参数值使用 numeric_limits
【发布时间】:2011-10-10 04:11:42
【问题描述】:

我有一个具有范围参数的模板统计类。

template <typename T>
class limitStats
{
public:
    limitStats(T mx, T min) :
      max(mx),
      min(mn),
      range(mx-mn)
    {;}

private:
    const T max;
    const T min;
    const T range;
}

我想把最大和最小允许值的默认值,但是浮点和整数类型的最小值不一样。

通常我会写

T min_val = numeric_limits<T>::isinteger ? numeric_limits<T>::min() : -numeric_limits<T>::max();

我发现不能作为默认参数使用

limitStats(T mx = std::numeric_limts<T>::max(), 
           T mn = numeric_limits<T>::isinteger ? numeric_limits<T>::min() : -numeric_limits<T>::max())

有没有办法实现这样的目标?

【问题讨论】:

    标签: c++ templates numeric-limits


    【解决方案1】:

    您可能需要重新考虑您的设计。你想用std::numeric_limits 没有提供的limitStats 做什么?

    不要复制std::numeric_limits设计的坏处。例如,std::numeric_limits&lt;double&gt;::min() 的名称非常错误。最小双精度数是最大双精度数的加法倒数。 std::numeric_limits 是对符号的滥用和对模板的滥用。在我看来,当然。

    你对min 的想法是错误的。考虑一下您对limitStats&lt;unsigned int&gt; 的默认设置。

    默认情况下,range 对于有符号整数无效。对于无符号整数,它会复制max,假设您使用limitStats&lt;unsigned int&gt;::min 解决了问题。对于浮点类型,它要么无效,要么复制max,具体取决于您所说的limitStats&lt;floating_point_type&gt;::min

    允许默认值是否有意义?如果您根本不提供默认值并使默认构造函数私有/未实现,您甚至不会有这个问题。

    【讨论】:

      【解决方案2】:

      有太多的语法错误和拼写错误,很难判断其中哪一个是您的问题。

      numeric_limits 是一个模板,因此您可以使用numeric_limits&lt;int&gt;::is_integer 或模板类型numeric_limits&lt;T&gt;::max() 访问它。

      【讨论】:

        【解决方案3】:

        【讨论】:

        • 这也将出现在 C++0x 中,如 std::numeric_limits&lt;T&gt;::lowest()
        【解决方案4】:

        在尝试创建 DLL 时,在 Visual Studio 上的 Windows 中尝试如下所示的函数签名时,我遇到了同样的问题

        int
        GetARandomNum(
            int lowest = std::numeric_limits<int>::min(),
            int highest = std::numeric_limits<int>::max());
        

        在尝试各种东西时,我决定从stdafx.h 中删除#inlcude &lt;windows.h&gt;,然后一切都开始正常了。鉴于在 VS 中默认选择了“stdafx.h”并且不包含它对构建错误没有任何影响,我决定简单地将 #inlcude &lt;windows.h&gt;stdafx'h 移动到需要的 cpp 文件中,以防万一DLL 项目通常仅在 dllmain.cpp 中。我不知道为什么Windows.h 会弄乱 C+11 标头,但我之前也看到过类似的问题。

        【讨论】:

          猜你喜欢
          • 2014-10-04
          • 2021-09-23
          • 2012-08-01
          • 2014-08-18
          • 2012-07-05
          • 1970-01-01
          • 2022-11-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多