आप 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();
}
}
यह सुविधा सी ++ 11 के बाद से ही उपलब्ध है। यदि आप सी ++ 03 के साथ फंस गए हैं, तो Boost's static assert macro पर एक नज़र डालें।
इसका पूरा विचार अच्छा त्रुटि संदेश है। आप उन लोगों के लिए परवाह नहीं है, तो या यहाँ तक कि नहीं बढ़ावा 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
}
[Static_assert] पर एक नज़र डालें (http://en.cppreference.com/w/cpp/language/static_assert) – juanchopanza
@juanchopanza: यह उत्तर है। – Nawaz
यह बहुत अच्छा लग रहा है! लेकिन क्या कुछ पूर्व-सी ++ 11 है? – MciprianM