Static const integer class member in a header-only file - right way?

Let's say I have the following example:

#include <cstdlib> class A { public: static const std::size_t value = 42; }; 

In short, I have (or better, want) a class A with a static const std::size_t element named value with a value of 42 (defined at compile time).

Now, IIRC, this only works under certain circumstances. For example, this is not the case if you take the address A::value . For this to work fine in all cases, you need to add a definition to some implementation file:

 const std::size_t A::value; 

However, I cannot do this because I want this file to be for the header only . Another common solution is the following:

 class A { public: enum { value = 42 }; }; 

I also don't like this solution because I would like the A::value type to be std::size_t .

What is a good solution to this problem? Preferably a small and portable solution, rather than something with a huge macromar, such as BOOST_STATIC_CONSTANT .


I need a solution for C ++ 03, not C ++ 11 (there it is trivial).

+7
source share
1 answer

First of all, using the unsigned size_t type for numbers, you are likely to run into implicit promotion problems. So, it's nice to use your corresponding signed type called ptrdiff_t . Which, as it happens, is a type of result of expressing the difference of pointers.

In addition, due to changes in C ++ 11, it is usually recommended to include <stddef.h> rather than <cstddef> , i.e. write ::ptrdiff_t or just just ptrdiff_t , not std::ptrdiff_t .

Now, how to make the extern header file, bind the constant thing:

 template< class Dummy > struct A_constants_ { static ::ptrdiff_t const value; }; template< class Dummy > ::ptrdiff_t const A_constants_<Dummy>::value = 42; typedef A_constants_<void> A_constants; class A : public A_constants { public: // Whatever }; 

Then you can use it as follows:

 foo( A::value ); 

There are other ways to do this, but above all, the simplest and easiest way to get right.

+8
source

All Articles