1

What is the C++ way to calculate some values using template params?

template<typename T, size_t SIZE>
class ThreadSafeArray
{
private:
    static const size_t BLOCK_SIZE = SIZE > 32 ? 16 : 4;
    static const size_t MUTEX_COUNT = SIZE / BLOCK_SIZE + 1;
    ...
};

or this

template<typename T, size_t SIZE>
class ThreadSafeArray
{
private:
    enum
    {
        BLOCK_SIZE = SIZE > 32 ? 16 : 4,
        MUTEX_COUNT = SIZE / BLOCK_SIZE + 1
    };
        ....
};

or somehow else?

Manu343726
  • 13,969
  • 4
  • 40
  • 75
Evgeny Eltishev
  • 593
  • 3
  • 18

2 Answers2

2

The enum hack is the old way to provide compile-time computations. It was used when in class initialization is not supportted by some compilers, so static const cannot be used. Nowadays its fixed in all modern compilers. So the preferred way is to use static const.

Check this answer for more info.

Community
  • 1
  • 1
Manu343726
  • 13,969
  • 4
  • 40
  • 75
1

The "enum hack" works with really old compilers that don't implement static const correctly (mostly pre-standard ones).

Unless you have no choice but to develop for such ancient tools, the static const version is clearly preferable.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111