JensB
JensB

Reputation: 939

Is there a way to create "empty" types to use for class templates?

I have a class template that looks like this:

template <typename T>
class TextureIcon
{
    static std::unique_ptr<Texture> s_texture_;
public:
    static void setTextureFile(std::string&& filePath);

    static std::unique_ptr<TextureIcon<T>> instance();
private:
    TextureIcon();
    sf::Sprite sprite_;
};

The idea is that it can be used to create icons that all use the same texture, like this:

class FlowerTexture;

int main()
{
    TextureIcon<FlowerTexture>::setTextureFile("flower-texture.png");
    
    auto flower1 = TextureIcon<FlowerTexture>::instance();
    auto flower2 = TextureIcon<FlowerTexture>::instance();
    auto flower3 = TextureIcon<FlowerTexture>::instance();
}

This works as intended, but I'm a bit unsatisfied with the use of class to create the types to use for the different TextureIcon-classes, as it looks like forward declarations for classes that will be implemented later.

So I'm wondering: Is there a keyword for creating "empty" types with no implementation? Something like this:

DefineType MyType;

Upvotes: 0

Views: 164

Answers (1)

NathanOliver
NathanOliver

Reputation: 180935

Instead of using types, you can use an enum class to create different texture enumerations and then have that enumeration type as a non-type template parameter for the TextureIcon class. That would look like

enum class Textures { Flower, Leaf, Branch };

template <Textures T>
class TextureIcon
{
    static Textures s_texture_;
public:
    static void setTextureFile(std::string&& filePath);

    static std::unique_ptr<TextureIcon<T>> instance();
private:
    TextureIcon();
    int sprite_;
};

int main()
{
    TextureIcon<Textures::Flower>::setTextureFile("flower-texture.png");
    
    auto flower1 = TextureIcon<Textures::Flower>::instance();
    auto flower2 = TextureIcon<Textures::Flower>::instance();
    auto flower3 = TextureIcon<Textures::Flower>::instance();
}

This lets you declare all the different types of textures you want to support in one place and keeps the namespace from getting cluttered with a bunch of empty types.

Upvotes: 1

Related Questions