jeudi 10 décembre 2020

Getting the maximum allowed value for a member variable in C++11

I am using an external library which defines a struct with an unsigned int C-style array:

struct Foo
{
    unsigned int bar[8];
}

In my code, I want to get the numeric_limits::max() for that type in order to check out of bounds values, and avoid passing overflowed values to the library.

So I do :

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;
}

This works, but is there a more elegant c++11 way not implying declaring a variable? If I use decltype(Foo().bar[0]) I have an error, as this returns a reference type, which numeric_limits doesn't like.

Aucun commentaire:

Enregistrer un commentaire