首页 > 解决方案 > 在 C++11 中获取成员变量的最大允许值

问题描述

我正在使用一个外部库,它定义了一个带有 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++11templatestypesdecltype

解决方案


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

您可以使用 删除参考零件std::remove_reference

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

推荐阅读