I am designing an abstract particle class for a game I'm writing in C++. Each derived particle class will have a different texture used by all instances of that class. Naturally, I'd like to use static members to store the textures. However, the textures are loaded, unloaded, and drawn identically for every particle. Thus I'd also like to write those functions in the base particle class rather than rewriting them for each derived class. The problem is that there's no way in C++ to create a static, virtual member.
I have found a couple suggestions on related Stack Overflow questions (here, here, and here). The two common suggestions are as follows:
- Create a virtual method (say,
texture
) in the base class that returns a reference to the texture object, and override that method in each derived class. - Use the curiously recurring template pattern to allow me to call the derived class's static member from the base class methods.
These are both good solutions, but neither seems quite ideal for my purposes.
I can't use (2) because since the derived classes don't share a common base class, I can't use polymorphism to store pointers to a mixture of different derived particles. Thus I'd need a separate container for each type of particle I want to add to the scene, which is not very maintainable.
Option (1) works perfectly for the draw
function. But as the question title alludes, I don't have an instance variable with which to call texture
from the load
and unload
methods. These methods ought to be static. Both functions are one-liners, so it's not difficult to just write those two functions for each subclass. However, it's a little less safe that way since there's nothing forcing me to implement those functions, even though they ought to be required for each subclass. Also, I'd just like to know if there's a better solution in case I or someone else runs into this issue with a class hierarchy with more complex methods (requiring more code duplication).
It's possible there is no better solution, but I thought I'd ask to see if anyone here can think of one or perhaps explain how I can otherwise improve my design to avoid the issue.
Edit: Here is an example implementation of option (1), since Kerrek SB pointed out my question is lacking code.
class BaseParticle
{
public:
// Cannot declare virtual load and unload methods because they're static.
void draw()
{
texture().draw();
}
protected:
virtual Texture& texture() = 0;
};
class DerivedParticle : public BaseParticle
{
public:
static void load() // Need to reimplement for every other derived class.
{
_texture.load();
}
static void unload() // Need to reimplement for every other derived class.
{
_texture.unload();
}
private:
static Texture _texture; // Need to create for every derived class.
virtual Texture& texture() { return _texture; }
};
Hopefully my example and comments make the problem a little clearer. I'm essentially trying to avoid the boilerplate code imposed by each static method.