我在做一个小游戏,我有一个结构,包含精灵信息。精灵的一个成员可以是SDL_纹理,也可以是任何其他类型的。我编写这个结构是为了支持多个平台。我的整个代码引用了这个结构,并且根据它运行的平台,“texture”成员可以是任何类型:SDL_texture、kgl_Tex、byte[]等等。
如何创建具有灵活成员类型的结构,并允许我的代码支持多平台特定类型?顺便说一句,我是美国国家标准学会的。
这里有一个更“真实”的例子来说明我在寻找什么:
typedef struct
{
int frames;
int x;
int y;
? *texture;
} Sprite;
void load_sprite()
{
Sprite sprite;
sprite.texture = load_sdl_sprite('test.png'); // This will return a SDL_Texture*
sprite.texture = load_kgl_sprite('test.png'); // This will return a kgl_tex*
sprite.texture = load_lib_sprite('test.png'); // This will return a sprite_t*
}
最佳答案
如果它只是一个值,基本上是“指针”,我可能会通过给指针加上别名来解决这个问题,每个平台都有一个不同的别名:
#if defined WITH_SDL
#include SDL-specific headers
typedef SDL_Surface Texture;
#elif defined WITH_KGL
#include KGL-specific headers
typedef kgl_tex Texture;
#elif defined WITH_LIB
#include LIB-specific headers
typedef sprite_t Texture;
#else
#error Undefined platform, no Texture representation.
#endif
typedef struct
{
int frames;
int x;
int y;
Texture *texture;
} Sprite;
这有一个(史诗般的)胜利,那就是保留了平台首选的本地类型。在不为其他平台构建时,它也避免提及其他平台的类型,这可能是一个很大的胜利。
typedef
层可能会在给SDL_Surface *
类型的指针分配Texture *
类型的值时引入警告。如果发生这种情况,那么就可以typedef void Texture
并完成它。您应该将以上内容放在特定于应用程序的头(
sprite.h
)或其他文件中,然后将其放在需要创建#include
的所有文件中。您的示例代码不太可信;您永远不会有三次调用不同的api,它们在彼此之后就这样做了。通常,您会使用上面这样的预处理器符号,或者使用Texture
、sprite-sdl.c
等。在那些实现sprite-kgl.c
功能的文件中,您将需要Sprite
执行上述操作。我还添加了特定于API的includes作为占位符,这是一种方法。