Topic: Suggestion for templates vs Macro based class.
Author: c.r.wood@gte.net.no_spam ("Charles Wood")
Date: Thu, 27 Feb 2003 19:20:54 +0000 (UTC) Raw View
A poster on CLC++ asked for an enum alternative, so after some work I
came up with this:
namespace std { }
#include <set>
#include <iostream>
#include <function>
#include <algo>
using namespace std;
#define eenum(V) \
class ebucket_##V { \
public: \
set< int, less< int> > my_set; \
void add(int v) { \
my_set.insert(my_set.begin(),v); \
} \
int min() { \
if (my_set.size() == 0) return 0; \
return *my_set.begin(); \
} \
int max() { \
if (my_set.size() == 0) return 0; \
return *(--my_set.end()); \
} \
}; \
\
ebucket_##V enum_##V; \
\
class item_##V { \
public: \
int i; \
item_##V(ebucket_##V &ref,int val) { \
ref.add(val); \
i = val; \
} \
operator int() {return i;}\
} \
void print_int(int a) {
cout << "Value: " << a << endl;
}
int main() {
eenum(colors);
item_colors red(enum_colors,0xff0000);
/* If possible, can we remove the owner from this call? */
item_colors green(enum_colors,0x00ff00);
item_colors blue(enum_colors,0x0000ff);
eenum(my_dogs);
item_my_dogs miluda(enum_my_dogs,1);
item_my_dogs tiger(enum_my_dogs,2);
cout << "Colors:" << enum_colors.my_set.size() << endl;
cout << "MY Dogs:" << enum_my_dogs.my_set.size() << endl;
cout <<"Miluda = " << miluda << endl; //o(1) or o(0) access here.
cout << "Min/Max of enum_my_dogs" << endl;
cout << "Min = " << enum_my_dogs.min() << endl; //o(1) if possible
cout << "Max = " << enum_my_dogs.max() << endl; //o(1) if possible
cout << "List of dogs" << endl;
for_each(enum_my_dogs.my_set.begin(), enum_my_dogs.my_set.end(),
print_int);
cout << "List of Colors" << endl;
for_each(enum_colors.my_set.begin(), enum_colors.my_set.end(), print_int);
return 0;
}
I was unable to use templates to accomplish this (the end effect
(main) ). Anyone here want to take a stab at templatizing it? Using macros
classes seems like more a hack than a solution, and I just don't know how to
get templates (which is safer) to accomplish this.
The goals are:
O(0) or O(1) accessing to variable value, aka int value = miluda *
5;
Access to min/max and for_each for that "class" of custom enums.
Thanks.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]