user997112
user997112

Reputation: 30625

Using const int class member in typedef?

I have this whilst compiling with C++11:

class A{
    const uint32_t X = 5;
    typedef std::array<B, X> ARRAY;

};

and I get the error message

Invalid use of non-static data member.

I don't wish to make this static because I had a few dynamic linking problems due to this and I don't wish to use initialiser lists because I would like these "magic numbers" to be very clear the top of the header.

Upvotes: 0

Views: 83

Answers (2)

Bathsheba
Bathsheba

Reputation: 234775

The very old-fashioned way of doing this is to #DEFINE X 5; Nobody uses this any more unless they want a slap on the wrist in the code review session.

The quite old-fashioned way of doing this is to use enum {X = 5}; In my opinion this is the best pre C++11 way.

The modern way of doing this is to use static constexpr uint32_t X = 5;

All these ways ensure that X is compile-time evaluable.

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

An alternative approach is

class A{
    enum Array_Size : uint32_t { X = 5 };
    typedef std::array<B, X> ARRAY;

};

Upvotes: 0

Related Questions