I am looking to create a method that can return a generic type and then this generic type can be handled by other methods that I have specifically defined.
PCCommand CrossPlatform::GetCommandPC();
XboxCommand CrossPlatform::GetCommandXbox();
? CrossPlatform::GetCommand()
{
#if PLATFORM == 1
//PC
return GetCommandPC();
#elif PLATFORM == 2
//xbox
return GetCommandXbox();
#endif
}
Both GetCommandPC and GetCommandXbox return different types, so how would I return them as a generic type in C++? The issue with templates, unless I'm mistaken would be that I'd have to pass a type into this function, but I wouldn't know what type to pass as the preprocessor checks would determine what platform is being used.
At the moment the PCCommand and XboxCommand are enum classes, so I'm not sure if it's possible to use a base type with enum classes.
Is there any way to achieve this, or a better way to achieve this?
For cross platform types that are controlled by #defines:
PCCommand CrossPlatform::GetCommandPC();
XboxCommand CrossPlatform::GetCommandXbox();
#if PLATFORM == 1
typedef PCCommand CrossPlatformCommand;
#elif PLATFORM == 2
typedef XboxCommand CrossPlatformCommand;
#endif
CrossPlatformCommand CrossPlatform::GetCommand()
{
#if PLATFORM == 1
//PC
return GetCommandPC();
#elif PLATFORM == 2
//xbox
return GetCommandXbox();
#endif
}
Since you are using conditional compilation, and assuming you only need one of the types (i.e. the one for the platform you are running on); the cleanest thing you can do is having a single Command type, which is the correct one in each case:
enum class Command
{
#if PLATFORM == 1
// PC
// ...
#elif PLATFORM == 2
// xbox
// ...
#endif
};
Think about it this way: when you are on e.g. PC, all the code for the other platforms is dead code (it won't be used, it won't be compiled, it might not even be able to be compiled!). And a general good practice is avoiding dead code lying around!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With