gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:03:50 26 4
gpt4 key购买 nike

我有以下模板化结构:

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 是否为非负数?

最佳答案

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

关于c++ - 当模板化类不包含可用的成员函数时,如何在编译时验证模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3881165/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com