2012-03-03 72 views
5

限制假设我有以下模板C++模板:如何把无类型在编译时间

template<unsigned char I, unsigned char F> 
class FOO 
{ 
    .... 
} 

其实,我需要(我> = F)。如果有人误用

FOO<1, 2> a; 

我希望提出一个编译错误。怎么做?

感谢

回答

8

一种方式可以是C++ 11的static_assert,这是类似于assert,但在编译时检查:

template<unsigned char I, unsigned char F> 
class FOO 
{ 
    static_assert(I >= F, "I needs to be larger or equal to F"); 
    ... 
}; 
+4

'static_assert'是一个声明。它可以出现在课堂范围内。 – kennytm 2012-03-03 08:02:53

+0

@KennyTM啊好的,所以我可以把它放在类定义中?不错,不知道(反正,还没有大量使用它)。 – 2012-03-03 08:15:05

6

如果你没有C++ 11,这个老式的数组边界技巧也适用于这里。只要把下面的在类的私有部分:

static int const error_size = I >= F ? 1 : -1; 
typedef char ERROR_I_must_not_be_less_than_F[error_size]; 

这将触发一个“负数组大小”错误,每当I小于F

+1

或者只是'typedef char ERROR_I_must_not_be_less_than_F [I-F];' – MSalters 2012-06-21 08:53:32

+0

@ MSalters:呃...是的。 +1 – Xeo 2012-06-21 09:53:35