如何在C/C++中进行更多的预处理

How to preprocess more in C/C++

本文关键字:预处理 C++      更新时间:2023-10-16

我很想知道,一些比我知识渊博的人可能会知道答案:

为什么C(在我的例子中是针对C++的(预处理器不更完整?

我的意思是,为什么我们不能使用例如C++作为预处理器语言?它将允许我们做更多关于类的事情,生成动态代码等

理想情况下,我想像预处理器宏一样调用C++函数,举一个具体的例子,我想做一些事情,比如:

#void generateVariable(std::string type, std::string name) {
#    if (name[0] == 'p')
#        cout << "protected:" << endl << type << " " << name << ";" << endl;
#    if (name[0] == 'm')
#        cout << "public:" << endl << type << " " << name << ";" << endl;
#    std::string prefix = name;
#    prefix.erase(2, npos);
#    name.erase(0,2);
#    name[0] = toupper(name[0]);
#    cout << "public:" << endl << type << "get" << name << "() const { return " << prefix+name << "; }" << endl;
#}

这样我就可以打电话给

class A {
    generateVariable(static const int, p_age)
}

它会产生

class A {
    protected:
        static const int p_age;
    public:
        static const int getAge() const { return p_age; }
}

有没有真正的方法来做这种事情,而不是用脚本语言解析整个文件并重写它?

预处理器实际上可以这样做(尽管我不建议这样做(:

#define generateVariable(__type__, __name__) 
    protected: __type__ __name__; 
    public: __type__ get##__name__() { return __name__; }
class A {
     generateVariable(static const int, p_age);
}

get##__name__()将扩展到getp_age()。。。