1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| #include <iostream>
using namespace std;
class Class {
public:
Base() : ptr(NULL), size(0), saved_index(0) {
}
protected:
void *ptr;
size_t size, saved_index;
};
typedef enum { ct_none, ct_no_nulls, ct_index_bounds, ct_memory_leaks } check_type_t;
class CheckBase {
public:
void do_check() const {
if (!check())
cerr << "<< ERROR : check failed ! >>" << endl;
}
protected:
virtual bool check() const = 0;
}
template<class T, int check_type>
class Check : public CheckBase {
};
template<int check_type>
class Check<Class, check_type> : public CheckBase {
public:
Check(Class *cls) : _cls(cls) {
}
protected:
bool check() const {
bool bCheckResult = true;
if(check_type & ct_no_nulls)
bCheckResult = bCheckResult && (_cls->ptr != NULL);
if(check_type & ct_index_bounds)
bCheckResult = bCheckResult && (_cls->saved_index < _cls->size);
if(check_type & ct_memory_leaks)
bCheckResult = bCheckResult && (_cls->ptr == NULL);
if(check_type & ct_index_bounds)
bCheckResult = bCheckResult && (_cls->saved_index < _cls->size);
}
protected:
Class *_cls;
};
int main() {
Class c;
Check<ct_none> ck1(&c);
Check<ct_no_nulss> c2(&c);
Check<ct_index_bounds | ct_memory_leaks> c3(&c);
c1.do_check();
c2.do_check();
c3.do_check();
return 0;
} |
Partager