Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 获取C+中成员变量的最大允许值+;11_C++_C++11_Templates_Types_Decltype - Fatal编程技术网

C++ 获取C+中成员变量的最大允许值+;11

C++ 获取C+中成员变量的最大允许值+;11,c++,c++11,templates,types,decltype,C++,C++11,Templates,Types,Decltype,我使用的是一个外部库,它定义了一个带有无符号int C样式数组的结构: struct Foo { unsigned int bar[8]; } 在我的代码中,我希望获取该类型的数值_limits::max(),以便检查越界值,并避免将溢出值传递给库 因此,我: auto n = Foo().bar[0]; if(myBar > std::numeric_limits<decltype (n)>::max()) { error("The Foo lib

我使用的是一个外部库,它定义了一个带有无符号int C样式数组的结构:

struct Foo
{
    unsigned int bar[8];
}
在我的代码中,我希望获取该类型的数值_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;
}
auto n=Foo().bar[0];
如果(myBar>std::numeric\u limits::max())
{
错误(“Foo库不支持那么大的条”);
返回false;
}

这是可行的,但是有没有更优雅的c++11方法不意味着声明变量?如果我使用
decltype(Foo().bar[0])
我有一个错误,因为这会返回一个引用类型,而
数值限制不喜欢它。

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

可以使用删除参考零件

std::数值限制

您可以有如下内容:

#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;
}
#包括
#包括
结构Foo{
无符号整型条[8];
};
int main(){
自动最大值=标准::数值限制::最大值();
返回0;
}
删除成员的“数组部分”。其优点是,这将适用于简单的
int
int[]
,以及多维数组。由于不使用
运算符[]
,因此也可以避免“参考问题”


如果您手头没有实例,可以确定
条的类型。

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

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

啊,太好了!这项工作做得很好,我可以很容易地将其放入模板函数中。@galinette对于模板,您可能需要
typename
关键字,如
typename std::remove\u reference::type
std::decation
是一个很好的选择(也可以删除常量)。
if (myBar > std::numeric_limits<std::remove_reference<decltype(std::declval <Foo>().bar [0])>::type>::max())
...