C++ 从模板参数中指定常量值

C++ 从模板参数中指定常量值,c++,templates,C++,Templates,我有一个带有模板参数的类,它是一个无符号int。在实现过程中,我必须经常使用以下表达式(SIZE是模板参数): 将该值放入编译时常量以避免每次使用时都写出整个表达式的最佳方法是什么 p、 s:如果可能的话,我想使用C++03。您可以: template <unsigned SIZE> class C { public: static const unsigned NumWords=(SIZE + sizeof(unsigned int) - 1) /

我有一个带有模板参数的类,它是一个无符号int。在实现过程中,我必须经常使用以下表达式(SIZE是模板参数):

将该值放入编译时常量以避免每次使用时都写出整个表达式的最佳方法是什么

p、 s:如果可能的话,我想使用C++03。

您可以:

template <unsigned SIZE>
class C
{
public:
    static const unsigned NumWords=(SIZE + sizeof(unsigned int) - 1) / 
                                   sizeof(unsigned int);
};
模板
C类
{
公众:
静态常量unsigned NumWords=(SIZE+sizeof(unsigned int)-1)/
sizeof(无符号整数);
};
根据编译器的不同,常量应在编译时可用:

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

C++11为这类问题提供了
constepr
,但您将答案限制为C++03。

propertname::value
?如果从多个不同的位置使用,这将最有效。
static const size\u t value=(…)
?“根据编译器的不同,常量应该在编译时可用”
static const
的问题是旧编译器没有在类初始化中实现。但是,正如我所指出的,旧的编译器。任何现代编译器都已经实现了这一点,而enum hack(解决问题的常用方法)是不需要的。
int array[C<24>::NumWords];