当模板类不包含可用的成员函数时,如何在编译时验证模板参数? [英] How do I validate template parameters in compile time when a templated class contains no usable member functions?

查看:241
本文介绍了当模板类不包含可用的成员函数时,如何在编译时验证模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模板 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 为非负数。我想强制执行一个编译时断言。

now that template requires Degree to be non-negative. I'd like to enforce a compile-time assert for that.

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

How do I do that? I tried to add a destructor to CPowerOfTen:

~CPowerOfTen() {
    compileTimeAssert( Degree >= 0 );
 }

但是由于它不是直接调用Visual C ++ 9决定不实例化它,因此编译时assert语句根本没有计算。

but since it is not called directly Visual C++ 9 decides not to instantiate it and so the compile-time assert statement is not evaluated at all.

如何对 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> {};

这篇关于当模板类不包含可用的成员函数时,如何在编译时验证模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆