[C++ compile time assertions]: Can we throw a compilation error if some condition is not met?
问题 I wrote a function: template<int N> void tryHarder() { for(int i = 0; i < N; i++) { tryOnce(); } } but I only want it to compile if N is in between 0 and 10. Can I do it? How? 回答1: You can do it with 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(); } } This feature is only avaliable since C++11. If you're stuck with C++03, take a look at Boost's static assert macro. The whole idea of