Define classes using C++ macros

Use the macro definition class of C++ to reduce the writing of repeated code under certain conditions

C++ macros can be implemented to name a class, the code is as follows:

#define MINE_CLASS(NAME) \
class Test##NAME \
{
      
                        \
    public: \
        Test##NAME() \
        {
      
       \
            std::cout<<"this is class: "<< #NAME<<std::endl; \
        }        \
}   ;             \


MINE_CLASS(LL);

int main() {
    
    
    TestLL a = TestLL();  //输出this is class LL
}

Among them, the ## of the macro is used to connect the two tags before and after.

Precautions for use:

It should be noted that creating classes with macro definitions has some limitations, such as not being able to define private constructors or member variables, etc. In addition, the class created by the macro definition will perform simple text replacement in the preprocessing stage, and cannot perform runtime operations such as type checking. Therefore, when using macro definitions to create classes, you need to carefully consider its usage scenarios and limitations.

Guess you like

Origin blog.csdn.net/qq_41841073/article/details/131569253