0

是否可以使用宏构造下面的类?

struct ModelName
{
public:
    typedef std::string type;

    static type get( const GameObject* obj )
    {
        return obj->getAttribute< type >( MODEL_NAME );
    }
};

换句话说,我想在编译时生成上面的代码,给定三个参数:ModelNameMODEL_NAMEstd::string。那可能吗?

编辑:输入后,我意识到我可以使用模板实现我想要的。出于某种原因,我认为它行不通。谢谢!

4

1 回答 1

4

当然:

#define DEFINE_ATTRIBUTE(classname, attributeName, attributeType)   \
        struct classname                                            \
        {                                                           \
            typedef attributeType type;                             \
                                                                    \
            static type get(const GameObject* const obj)            \
            {                                                       \
                return obj->getAttribute<type>(attributeName);      \
            }                                                       \
        }

(缺少分号是正常的;它强制/允许在宏之后使用分号。)

如果可能,您可以考虑将其重新设计为模板。

于 2013-01-03T22:51:24.027 回答