简体   繁体   English

如何在C ++中返回没有模板的泛型类型?

[英]How can I return a generic type without templates in 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++? GetCommandPC和GetCommandXbox都返回不同的类型,那么如何在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. 目前PCCommand和XboxCommand是枚举类,所以我不确定是否可以使用带枚举类的基类型。

Is there any way to achieve this, or a better way to achieve this? 有没有办法实现这一目标,或者更好的方法来实现这一目标?

For cross platform types that are controlled by #defines: 对于由#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 (ie 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: 你能做的最干净的事情是拥有一个Command类型,在每种情况下都是正确的:

enum class Command
{
    #if PLATFORM == 1
        // PC
        // ...
    #elif PLATFORM == 2
        // xbox
        // ...
    #endif
};

Think about it this way: when you are on eg 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!). 以这种方式思考:当你在PC上时,其他平台的所有代码都是死代码 (它不会被使用,它不会被编译,甚至可能无法被编译!)。 And a general good practice is avoiding dead code lying around! 一般的良好做法是避免死lying!

You can use inheritance. 您可以使用继承。 Create a super class Command and make PCCommand and XboxCommand subclasses and then in your function return a Command. 创建一个超类Command并生成PCCommand和XboxCommand子类,然后在函数中返回一个Command。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM