1

I have a class with a template argument what is an unsigned int. During implementation, I have to use the following expression a lot of time (SIZE is the template parameter):

(SIZE + sizeof(unsigned int) - 1) / sizeof(unsigned int)

What is the best way to put this value to a compile time constant to avoid writing out the whole expression every time I want to use it?

p.s.: I want to use the C++03 if possible.

2
  • AppropriateName<SIZE>::value? That would work best if this is being used from multiple separate places.
    – chris
    Aug 14, 2013 at 21:04
  • 4
    static const size_t value = (...)?
    – Rapptz
    Aug 14, 2013 at 21:06

1 Answer 1

3

You can do:

template <unsigned SIZE>
class C
{
public:
    static const unsigned NumWords=(SIZE + sizeof(unsigned int) - 1) / 
                                   sizeof(unsigned int);
};

Depending on your compiler, the constant should be usable at compile time:

int array[C<24>::NumWords];

C++11 offers constexpr for this sort of thing, but you limited the answer to C++03.

1
  • "Depending on your compiler, the constant should be usable at compile-time" The problem with static const is that old compilers didn't implement in class initialization. But, as I noted, old compilers. Any modern compiler have implemented that, and the enum-hack (The common way to solve the problem) is not needed.
    – Manu343726
    Aug 14, 2013 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.