Static Members - Easier Way?
Oct 1, 2010 at 12:18pm UTC
I was wondering if there was a better way for a static member function to access each an every class than this:
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
struct Staticlass
{
int Int;
private :
static vector<Staticlass*> List;
public :
Staticlass()
{
Int = 0;
List.push_back(this );
}
~Staticlass()
{
for (unsigned long i = 0; i < List.size(); ++i)
{
if (List[i] == this )
{
List.erase(List.begin() + i);
return ;
}
}
}
static void AddAll()
{
for (unsigned long i = 0; i < List.size(); ++i)
{
++(List[i]->Int);
}
}
static void PrintAll()
{
for (unsigned long i = 0; i < List.size(); ++i)
{
cout << (List[i]->Int) << endl;
}
}
};
vector<Staticlass*> Staticlass::List;
Note this is just a test, and it seems to work well. But as I said above, I wonder if I am overcomplicating the process?
Oct 1, 2010 at 12:41pm UTC
Well, what are you trying to do?
This works, though you have not accounted for copy construction.
There are shorter ways to write each of those functions, but they involve using boost::lambda.
Though your destructor could be written using just algorithms:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <algorithm>
#include <boost/lambda/lambda.hpp>
~Staticlass() {
List.erase( std::find( List.begin(), List.end(), this ) );
}
static void AddAll() {
std::for_each( List.begin(), List.end(),
&boost::lambda::_1->*&Staticlass::Int += 1 );
}
static void PrintAll() {
std::for_each( List.begin(), List.end(),
std::cout << &boost::lambda::_1->*&Staticlass::Int << '\n' );
}
Oct 1, 2010 at 2:55pm UTC
Why you need to handle the collection in the same class?
1 2 3 4 5 6 7 8
class A{
ContA *where_I_belong; //Cont & if is you can't change ownership
//...
};
class ContA{
std::vector<A*> List;
//all the algorithms of a collection (add, erase, update, print ...)
}
Last edited on Oct 1, 2010 at 3:17pm UTC
Oct 1, 2010 at 3:01pm UTC
Does a set help?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
struct Staticlass
{
int Int;
private :
static set<Staticlass*> List;
public :
Staticlass()
{
Int = 0;
List.insert(this );
}
~Staticlass()
{
List.erase(this );
}
//...
};
//...
vector<Staticlass*> Staticlass::List;
//...
Last edited on Oct 1, 2010 at 3:02pm UTC
Topic archived. No new replies allowed.