this is an ideal use case for python cog
see also this answer .
I used cog to create handlers for the event list, the handler code is very general, and I do not need to do special cases, but I still have to write all the functions, so I made the events in the list in the .py file and the code to generate the handler template in the function python. so I can be true to the DRY principle
obviously you will need to add cog to the pre-build of your makefile to work with your toolchain
To change as an example the development of the code needed to add a template to your classes, I would do something like:
myCodeGeneration.py
import cog ClassesToMock = [ [ 'IfaceA' , 'classA' , 'mockA' , ['void doSomething(int foo)' , 'int getSomething()'] , [ 'IfaceB', 'classB' , 'mockB' , ['static classA& getInstance()'] ] def addInterfaces( myStructure ): for classItem in myStructure: cog.outl('class %s { ' % classItem[0] ) for methodDecl in classItem[3]: cog.outl(' virtual %s = 0;' %methodDecl ) cog.outl(' } ') #implement your real classes normally def addMocks( myStructure ): for classItem in myStructure: cog.outl('class %s : public %s { ' % classItem[2] % classItem[0] ) for methodDecl in classItem[3]: cog.outl(' %s {' %methodDecl ) cog.outl(' MOCK_STUFF_MACRO ') cog.outl(' } ') cog.outl(' } ')
then in your header:
IfaceA.h
/*[[[cog import cog import myCodeGeneration myCodeGeneration.addInterfaces( [ [ 'IfaceA' , 'classA' , 'mockA' , ['void doSomething(int foo)' , 'int getSomething()'] ] ) ]]]*/ //your code will be generated here //[[[end]]]
mockA.h
/*[[[cog import cog import myCodeGeneration myCodeGeneration.addMocks( [ [ 'IfaceA' , 'classA' , 'mockA' , ['void doSomething(int foo)' , 'int getSomething()'] ] ) ]]]*/ //your code will be generated here //[[[end]]]
Also, the problem of considering adding python to your C ++ source โpollutesโ it or โdecoratesโ it is largely a matter of taste and style. I believe cog provides an addition to metaprogramming a template style that C ++ does not have, providing tools for the programmer to ensure the code is clear and legible. But I do not expect everyone to agree.
For me, the whole principle of architectural design that underlies this approach, Do not repeat yourself . errors occur when we must manually encode a method in several places. Let the computer automate what it automates and encodes things that can happen more than once. As a side effect, it will make your coding more enjoyable, both for writing it and reading it later.
hope this helps