我有一个以下模板化的结构:
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() { compileTimeAssert( Degree >= 0 ); }
但由于它没有被直接调用,因此Visual C 9决定不实例化它,因此根本不评估编译时断言语句.
如何对Degree为非负的强制执行编译时检查?
解决方法
template<bool> struct StaticCheck; template<> struct StaticCheck<true> {}; template<int Degree> struct CPowerOfTen : StaticCheck<(Degree > 0)> { enum { Value = 10 * CPowerOfTen<Degree - 1>::Value }; }; template<> struct CPowerOfTen<0> { enum { Value = 1 }; };
编辑:没有无限递归.
// Help struct template<bool,int> struct CPowerOfTenHelp; // positive case template<int Degree> struct CPowerOfTenHelp<true,Degree> { enum { Value = 10 * CPowerOfTenHelp<true,Degree - 1>::Value }; }; template<> struct CPowerOfTenHelp<true,0> { enum { Value = 1 }; }; // negative case template<int Degree> struct CPowerOfTenHelp<false,Degree> {} // Main struct template<int Degree> struct CPowerOfTen : CPowerOfTenHelp<(Degree >= 0),Degree> {};