2013-04-24 86 views
6

我写了一个函数:[C++编译时断言]:如果不满足某些条件,我们可以抛出一个编译错误吗?

template<int N> void tryHarder() { 
    for(int i = 0; i < N; i++) { 
     tryOnce(); 
    } 
} 

但我只希望它来编译,如果N是介于0和10.我能做到吗?怎么样?

+6

看看[static_assert](http://en.cppreference.com/w/cpp/language/static_assert) – juanchopanza 2013-04-24 12:56:04

+0

@juanchopanza:这就是答案。 – Nawaz 2013-04-24 12:57:08

+0

它看起来不错!但是,有什么预先C++ 11? – MciprianM 2013-04-24 13:03:40

回答

13

你可以用static_assert declaration做到这一点:

template<int N> void tryHarder() { 

    static_assert(N >= 0 && N <= 10, "N out of bounds!"); 

    for(int i = 0; i < N; i++) { 
     tryOnce(); 
    } 
} 

此功能只avaliable因为C++ 11。如果你坚持使用C++ 03,请看​​。

这是一个很好的错误信息。如果你不关心这些,或者甚至不能AFFOR提升,你可以做一些事情如下:

template<bool B> 
struct assert_impl { 
    static const int value = 1; 
}; 

template<> 
struct assert_impl<false> { 
    static const int value = -1; 
}; 

template<bool B> 
struct assert { 
    // this will attempt to declare an array of negative 
    // size if template parameter evaluates to false 
    static char arr[assert_impl<B>::value]; 
}; 

template<int N> 
void tryHarder() 
{ 
    assert< N <= 10 >(); 
} 

int main() 
{ 
    tryHarder<5>(); // fine 
    tryHarder<15>(); // error, size of array is negative 
} 
+0

这确实假设'N'是一个编译时间常数,tho'。 – 2013-04-24 12:59:13

+1

如果将其更改为template void tryHader(){static_assert(N <= 10,“N outbounds!”);' – Yakk 2013-04-24 12:59:17

+4

@MatsPetersson作为模板参数,它会变得稍微简单一些一个安全的假设是编译时间常数。 – Yakk 2013-04-24 12:59:56

-2
#if !defined(__cplusplus) 
#error C++ compiler required. 
#endif 

这仅仅是一个例子。

这里是源链接:http://msdn.microsoft.com/en-us/library/c8tk0xsk(v=vs.71).aspx

我要说的是,你可以使用#ERROR也

这是一个指令

编辑@Pratik Chowdhruy:我同意保罗R.这不直接回答这个问题。对不起,社区

+0

这不回答这个问题。 – 2013-04-24 13:01:20

+0

看看其他答案,了解问题出在这里--OP想知道如何对模板参数进行编译时断言,而不是如何使用条件编译和'#error'。 – 2013-04-24 13:24:24

+0

对不起保罗R – 2013-05-16 16:31:20