Assigning to a static const member a value coming from a function (from a static method, to be more precise)

StackOverflow https://stackoverflow.com/questions/18272727

  •  24-06-2022
  •  | 
  •  

Question

The following is not allowed ('std::numeric_limits::max()' cannot appear in a constant-expression):

#include <limits>   

struct MyStruct {

private:  
  static const unsigned int INVALID_VALUE = std::numeric_limits<unsigned int>::max();

public:
  unsigned int index;

  inline MyStruct() : index(INVALID_VALUE) {}
};

Which could be the best way to obtain the desired behaviour? I would like, if possible, to have INVALID_VALUE to be known at compile time (e.g. to allow the compiler doing better optimization).

Was it helpful?

Solution 2

How about define your constant as ~0U. Since unsigned int is defined to be "direct binary representation", the inverse thereof should be all bits set.

OTHER TIPS

You can use UINT_MAX from <climits> instead.

Alternatively, you can provide a definition:

struct MyStruct 
{
private:
  static const unsigned int INVALID_VALUE;
};

const unsigned int MyStruct::INVALID_VALUE = std::numeric_limits<unsigned int>::max();

Or, switch to C++11 where the function is constexpr and this is ok.

In C++11 or later, that should be fine since the numeric_limits functions are now declared constexpr.

If you're stuck in the past, then you'll need to define and initialise the constant outside the class:

// Header file
struct MyStruct {
    static const unsigned int INVALID_VALUE;
    // ...
};

// One source file
const unsigned int Mystruct::INVALID_VALUE = std::numeric_limits<unsigned int>::max();

Alternatively, you could use the UINT_MAX macro, defined in <climits>. This has the advantage that your constant will be usable in a constant expression.

Add:

const unsigned int mystruct::INVALID_VALUE = std::numeric_limits<unsigned int>::max();

somewhere in a cpp file, this is the normal way to initialize static members.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top