I have several classes and I want each one to have a static member, a list to keep track of their respective objects. getList() is the same function in each class except for the return type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Declaration only, I left out the implementation-definition
class Stuff1
{
private:
static std::list< Stuff1 > tally; // list to keep track of Stuff1 objects
public:
static std::list< Stuff1 > getList(); // returns the list
};
class Stuff2
{
private:
static std::list< Stuff2 > tally; // list to keep track of Stuff2 objects
public:
static std::list< Stuff2 > getList(); // returns the list
};
But I want to avoid rewriting/copying the same code for each class. I'm considering using a class template with static members.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Declaration only, I left out the implementation-definition
template< class Type >
class ListClass
{
private:
static std::list< Type > tally; // List for storing objects.
public:
static std::list< Type > getList(); // Returns the list
};
class Stuff1 : public ListClass< Stuff1 >
{
};
class Stuff2 : public ListClass< Stuff2 >
{
};
Is this allowed? I need Stuff1::tally to be different than Stuff2::tally. I am aware that if ListClass was a regular class (not a class template) ListClass::tally, Stuff1::tally, and Stuff2::tally reference the same thing.