Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a generic type without templates in C++?

Tags:

c++

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?

like image 792
user9942393 Avatar asked Dec 17 '25 23:12

user9942393


2 Answers

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

}
like image 155
Martin Bonner supports Monica Avatar answered Dec 20 '25 16:12

Martin Bonner supports Monica


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!

like image 33
Acorn Avatar answered Dec 20 '25 16:12

Acorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!