简体   繁体   English

我可以在这里使用模板吗?

[英]Can I use templates here?

I have the following piece of code: 我有以下代码:

int CreatePropertiesDialog(int type, void *object)
{
    if( type == 1 )
    {
        ClassA *a = static_cast<ClassA *>( object );
        // build the properties dialog
    }
    if( type == 2 )
    {
        ClassB *b = static_cast<ClassB *>( object );
        // build the properties dialog
    }
    // display the properties dialog
}

However, the use of void* type sounds very ugly. 但是,使用void*类型听起来很丑。

Can this code be improved by using template? 可以通过使用模板来改进此代码吗? Or maybe some other means? 还是其他一些方法?

You can ditch the type parameter altoghether and have two methods, one for ClassA or one for ClassB . 您可以一起放弃type参数,并有两种方法,一种用于ClassA或一种用于ClassB Like this: 像这样:

int CreatePropertiesDialog(ClassA *a)
{
        // build the properties dialog
        DialogConf conf = ...
        return displayDialog(conf);   
}


int CreatePropertiesDialog(ClassB *b)
{
        // build the properties dialog
        DialogConf conf = ...
        return displayDialog(conf);   
}

int displayDialog(DialogConf conf) {
    // ...
}

Or, you can have ClassA and ClassB responsible for building the configuration by each having a method that returns a DialogConf that contains the configuration and then pass it to displayDialog . 或者,你可以有ClassAClassB负责由每栋楼有一个返回的方法配置DialogConf包含配置,然后将它传递给displayDialog

Depends on how you call the code and what is the available data. 取决于您如何调用代码以及可用的数据是什么。

For example, if you have a bunchof void* : 例如,如果您有一堆void*

void** objects = get_objects();

CreatePropertiesDialog(type, objects[1]);

Then your input is all void* . 那么您的输入全部为void* Must must process it as is or refactor the code to not use void pointers. 必须必须按原样处理它或重构代码以不使用空指针。

If you have locals or variables of known types, then overloading might be appropriated: 如果您具有已知类型的局部变量或变量,则可能需要重载:

int CreatePropertiesDialog(ClassA*) {
    // ...
}

int CreatePropertiesDialog(ClassB*) {
    // ...
}

Without more information about what you have as input data it's hard to have a more precise answer. 如果没有更多关于输入数据的信息,那么很难获得更准确的答案。

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

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