Typename在C ++中作为参数传递

时间:2014-09-24 21:33:52

标签: c++ macros

我的朋友给了我一段代码,要求解释一下:

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);
}

我理解一般的想法,但我无法想象ALLOCATION函数的参数。我想这个代码:

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

更详细:

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

知道分配应该如何吗?

显然它是(Marco A.& dolan的代码):

ALLOCATION(X) (new X)

1 个答案:

答案 0 :(得分:1)

我最好的猜测是一个宏:

#define ALLOCATION(type) (new type)

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

这肯定有用,虽然它是一种可怕的编码风格和实践。

免责声明:这只是一个思想练习,并且不会为一个严肃的项目编写类似的代码。