News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ array tips - Handling array dimensions with statics

Started by ben2ong2, October 06, 2006, 04:57:53 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2


PROBLEM: You are not allowed to view links. Register or Login (Kevin J Hopps)

It appears as though a const int takes up memory just like a normal int,
except that it is read-only. 


RESPONSE: You are not allowed to view links. Register or Login (Jim Adcock), 14 Apr 93

[a]

Try using a static const int member.  Good compilers shouldn't use
any memory for this, unless you take its address.



The static const int member indeed cannot be given defined value inside
the class declaration, meaning it cannot be used for array sizing.  For
array sizing you'd be forced to use a class enum.

[c]

Most of what you want can be done, it just requires a lot of differing
and crappy hacks.  I believe there are proposals before the committee
for allowing constants to be defined within the class declaration,
which would seem to solve these current shortcomings.


RESPONSE: You are not allowed to view links. Register or Login (Jamshid Afshar)

[a]

Are you sure?  I could see how a smart linker could handle the
situations discussed here, but there's no way in general for the
compiler to know whether the static data member will be initialized
with a run-time expression.



Right.  I think the only situation where a compile-time constant is
required, besides an array size specification or preprocessor
expression, is when specififying a constant (non-type) template
argument.

   template<class T, T min, T max> class Range {/*...*/};
   typedef Range<double, 0, 360> Degree;
   //(actually, current compilers don't handle the above immediate
        // use of 'T', but I think ANSI is considering it)
   
[c]

I suggest using an inline static member function (unless of course
ANSI comes up with something better).  The constant will definitely be
inlined and you don't have to bother with a separate definition.  And
an extra set of parenthesis never killed anyone. :-)

   class Foo {
   public:
      static long MAXCOUNT() { return 5000000; }
      static unsigned MASK() { return 0xF0F0; }
   };
   ...
   if ( (x & Foo::MASK())!=0 && n<Foo::MAXCOUNT() )
      ...
You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login