c++ - 在 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
不喜欢的引用类型。
解决方案
对于像这样的左值表达式Foo().bar[0]
,decltype
产生类型T&
,即左值引用类型。
您可以使用 删除参考零件std::remove_reference
。
std::numeric_limits<std::remove_reference<decltype(Foo().bar[0])>::type>
推荐阅读
- java - 如何在 Java 中获取逗号和数字以外的字符?
- javascript - JSON获取由2个表过滤的资源
- php - 如果我卸载 wamp,如何获取 wordpress 帖子
- javascript - 我正在练习一个小型联系表格,我想在其中呈现带有用户名的完整视图
- docker - 在 /var/log/messages 中查看大量 docker 错误消息
- saiku - Saiku:如何获得 Saiku Pentaho 插件的许可证?
- c# - 在 MassTransit 中使用 ConfigureEndpoints 方法时,有没有办法配置特定的消费者?
- ios - 在 SWIFT 中关闭 segue 之前保存变量
- python-2.x - 如何解决python项目中的路径问题?
- authorization - 多租户微服务中的 RBAC