【问题标题】:Getting the maximum allowed value for a member variable in C++11在 C++11 中获取成员变量的最大允许值
【发布时间】:2020-12-10 10:06:46
【问题描述】:

我正在使用一个外部库,它定义了一个带有 unsigned int C 样式数组的结构:

struct Foo
{
    unsigned int bar[8];
}

在我的代码中,我想获取该类型的 numeric_limits::max() 以检查超出范围的值,并避免将溢出的值传递给库。

所以我这样做了:

auto n = Foo().bar[0];
if(myBar > std::numeric_limits<decltype (n)>::max())
{
    error("The Foo library doesn't support bars that large");
    return false;
}

这可行,但有没有更优雅的 c++11 方式不暗示声明变量?如果我使用decltype(Foo().bar[0]),我有一个错误,因为它返回一个引用类型,numeric_limits 不喜欢。

【问题讨论】:

    标签: c++ c++11 templates types decltype


    【解决方案1】:

    对于像Foo().bar[0] 这样的左值表达式,decltype 产生类型T&amp;,即左值引用类型。

    您可以使用std::remove_reference 删除引用部分。

    std::numeric_limits<std::remove_reference<decltype(Foo().bar[0])>::type>
    

    【讨论】:

    • 啊完美!这完美地完成了这项工作,我可以轻松地将其放入模板函数中。
    • @galinette 对于模板,您可能需要typename 关键字,例如typename std::remove_reference&lt;decltype(...)&gt;::type
    • std::decay 是一个不错的选择(也删除 constness)。
    【解决方案2】:

    作为@songyuanyao 答案的补充,您可以避免使用std::declval 实例化Foo,如下所示:

    if (myBar > std::numeric_limits<std::remove_reference<decltype(std::declval <Foo>().bar [0])>::type>::max())
    ...
    

    Live demo

    【讨论】:

      【解决方案3】:

      你可以有这样的东西:

      #include <limits>
      #include <type_traits>
      
      struct Foo {
        unsigned int bar[8];
      };
      
      int main() {
      
        auto max_val = std::numeric_limits<std::remove_all_extents_t<decltype(std::declval<Foo>().bar)>>::max();
      
      
        return 0;
      }
      

      std::remove_all_extents 删除您成员的“数组部分”。优点是这也适用于简单的intint [] 和多维数组。由于您不使用operator[],因此您也避免了“参考问题”。

      如果您手头没有实例,std::declval 允许确定 bar 的类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-08
        • 1970-01-01
        • 2023-04-02
        • 2011-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多