相关疑难解决方法(0)

当模板化类不包含可用的成员函数时,如何在编译时验证模板参数?

我有以下模板struct:

template<int Degree>
struct CPowerOfTen {
enum { Value = 10 * CPowerOfTen<Degree - 1>::Value };
};

template<>
struct CPowerOfTen<0> {
    enum { Value = 1 };
};
Run Code Online (Sandbox Code Playgroud)

这将是这样使用的:

const int NumberOfDecimalDigits = 5;
const int MaxRepresentableValue = CPowerOfTen<NumberOfDecimalDigits>::Value - 1;
// now can use both constants safely - they're surely in sync
Run Code Online (Sandbox Code Playgroud)

现在该模板需要Degree非负面的.我想为此强制执行编译时断言.

我怎么做?我试图添加一个析构函数CPowerOfTen:

~CPowerOfTen() {
    compileTimeAssert( Degree >= 0 );
 }
Run Code Online (Sandbox Code Playgroud)

但由于它没有被直接调用,因此Visual C++ 9决定不实例化它,因此根本不评估编译时断言语句.

我怎么能强制执行编译时检查Degree非负面?

c++ templates metaprogramming visual-c++

6
推荐指数
3
解决办法
2984
查看次数

标签 统计

c++ ×1

metaprogramming ×1

templates ×1

visual-c++ ×1