简体   繁体   中英

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.

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 . 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 .

Depends on how you call the code and what is the available data.

For example, if you have a bunchof void* :

void** objects = get_objects();

CreatePropertiesDialog(type, objects[1]);

Then your input is all 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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