我有一个看起来像这样的类模板:
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_;
};
这个想法是它可以用来创建所有使用相同纹理的图标,如下所示:
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();
}
这按预期工作,但我对使用 class
创建用于不同 TextureIcon
类的类型有点不满意,因为它看起来像类的前向声明稍后实施。
所以我想知道:是否有一个关键字可以创建没有实现的“空”类型? 像这样:
DefineType MyType;
答案 0 :(得分:1)
您可以使用 enum class
来创建不同的纹理枚举,而不是使用类型,然后将该枚举类型作为 TextureIcon
类的非类型模板参数。那看起来像
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();
}
这让您可以在一个地方声明您想要支持的所有不同类型的纹理,并防止命名空间被一堆空类型弄乱。