【问题标题】:elegant way to get a variables limit获得变量限制的优雅方法
【发布时间】:2016-08-29 16:44:27
【问题描述】:

有没有比

更好的方法来将变量设置为其限制之一
varname = std::numeric_limits<decltype(varname)>::max();

尤其是在初始化时

int64_t varname = std::numeric_limits<decltype(varname)>::max();

我通常不想在此类表达式中使用该类型,因为如果类型更改,它很容易错过。

【问题讨论】:

  • 我会安装一个变量模板:template &lt;typename T&gt; constexpr T max_val = std::numeric_limits&lt;T&gt;::max();,然后使用auto v = max_val&lt;int64_t&gt;;。在 C++17 中,我会制作模板 inline 并将其粘贴在标题中。

标签: c++ coding-style numeric-limits


【解决方案1】:

为了完整起见,走在合法的边缘:

#include <iostream>
#include <limits>

template<class T>
  T biggest(T&)
{
  return std::numeric_limits<T>::max();
}

int main()
{
  std::int64_t i = biggest(i);
  std::cout << i << std::endl;
  return 0;
}

【讨论】:

  • 我其实认为这是最简洁的方式。您认为这里的哪些内容不合法?
  • @MarcinZukowski 这是合法的,但只需要一个维护者以某种方式使用参数的值,它就变成了 UB。
【解决方案2】:

回复

我通常不想在此类表达式中使用该类型,因为如果更改类型很容易错过。

这很简单:

auto varname = std::numeric_limits<int64_t>::max();

您可以通过多种方式减少 std::numeric_limits 的详细程度,例如通过模板别名或定义函数模板。

template< class Type >
using Limits_ = std::numeric_limits<Type>;

auto varname = Limits_<int64_t>::max();

template< class Type >
constexpr auto max_of() -> Type { return std::numeric_limits<Type>::max(); }

auto varname = max_of<int64_t>();

在 C++14 及更高版本中,您可以将 max_of 设为模板变量,出于某种我从未见过解释的原因,有些人更喜欢。

【讨论】:

    【解决方案3】:

    汽车呢?

    auto varname = std::numeric_limits<int64_t>::max();
    

    只有一处提到类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多