【发布时间】:2011-04-22 07:45:49
【问题描述】:
我有以下模板struct:
template<int Degree>
struct CPowerOfTen {
enum { Value = 10 * CPowerOfTen<Degree - 1>::Value };
};
template<>
struct CPowerOfTen<0> {
enum { Value = 1 };
};
要这样使用:
const int NumberOfDecimalDigits = 5;
const int MaxRepresentableValue = CPowerOfTen<NumberOfDecimalDigits>::Value - 1;
// now can use both constants safely - they're surely in sync
现在模板要求Degree 为非负数。我想为此强制执行编译时断言。
我该怎么做?我试图给CPowerOfTen添加一个析构函数:
~CPowerOfTen() {
compileTimeAssert( Degree >= 0 );
}
但由于它不是直接调用的,Visual C++ 9 决定不实例化它,因此根本不评估编译时断言语句。
如何在编译时检查 Degree 是否为非负数?
【问题讨论】:
标签: c++ visual-c++ templates metaprogramming