1

使用模板参数计算某些值的 C++ 方法是什么?

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;
    ...
};

或这个

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

或以其他方式?

4

2 回答 2

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.

于 2013-07-23T06:41:59.737 回答
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.

于 2013-07-23T06:40:49.373 回答