Można to zrobić z 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();
}
}
Ta funkcja jest dostępna tylko od C++ 11. Jeśli utkniesz w C++ 03, spójrz na Boost's static assert macro.
Cała idea to miłe komunikaty o błędach. Jeśli nie dbać o tych, lub może nawet nie affor doładowania, można zrobić coś jak następuje:
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
}
Spójrz na [static_assert] (http://en.cppreference.com/w/cpp/language/static_assert) – juanchopanza
@juanchopanza: To jest odpowiedź. – Nawaz
Wygląda świetnie! Ale czy jest coś pre-C++ 11? – MciprianM