简体   繁体   中英

Typename passed as parameter in C++

My friend gave me a snipped of code asking to explain it:

typedef struct bia_motor {
    unsigned int attributes123;
} type_bia_motor;

typedef struct bia {
    int attributes456;
} type_bia;

type_bia_motor *constructor()
{
    return ALLOCATION(type_bia_motor);
}

I understand a general idea, but I cannot imagine the parameter of ALLOCATION function. I supposed this code:

type_bia_motor* ALLOCATION( ??? ) {
    return new type_bia_motor;
}

In more detail:

void* ALLOCATION( TYPENAME ) {
    // IF type_bia_motor IS NEEDED
        return new type_bia_motor;
    // IF type_bia IS NEEDED
        return new type_bia;
}

Any idea how ALLOCATION should look like?

Apparently it is (code by Marco A. & dolan):

ALLOCATION(X) (new X)

My best guess is a macro:

#define ALLOCATION(type) (new type)

type_bia_motor *constructor()
{
    return ALLOCATION(type_bia_motor);
}

this would definitely work, although it's a horrible coding style and practice.

Disclaimer: Let this just be an exercise of thought and don't ever write code like that for a serious project.

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