,如果你允許的Cog使用在你的項目,你的代碼變得更容易閱讀:
/*[[[cog
# definitions ----
import cog
def AddDeclaration(templateArg , restOfDeclaration):
cog.outl(' %s struct %s; ' % (templateArg , restOfDeclaration))
# generation ---
types = ['bool' , 'std::string']
names = ['Foo' , 'Bar']
for index in range(len(names)):
AddDeclaration('template<int, %s>' % types[index] , names[index])
]]]*/
//[[[end]]]
你在這個文件運行後嵌齒輪,你會得到:
/*[[[cog
# definitions ----
import cog
def AddDeclaration(templateArg , restOfDeclaration):
cog.outl(' %s struct %s; ' % (templateArg , restOfDeclaration))
# generation ---
types = ['bool' , 'std::string']
names = ['Foo' , 'Bar']
for index in range(len(names)):
AddDeclaration('template<int, %s>' % types[index] , names[index])
]]]*/
template<int, bool> struct Foo; <---------------- generated by Cog!!
template<int, std::string> struct Bar;
//[[[end]]]
你甚至可以將您的定義移至單獨的.py文件中,並且齒輪部分將如下所示:
declarations.py
import cog
def AddDeclaration(templateArg , restOfDeclaration):
cog.outl(' %s struct %s; ' % (templateArg , restOfDeclaration))
my.h
/*[[[cog
# definitions ----
import declarations
# generation ---
types = ['bool' , 'std::string']
names = ['Foo' , 'Bar']
for index in range(len(names)):
AddDeclaration('template<int, %s>' % types[index] , names[index])
]]]*/
template<int, bool> struct Foo;
template<int, std::string> struct Bar;
//[[[end]]]
使用COG的主要優點是,你獲得你的代碼生成的完全控制,完全使用升壓預處理或東西避免混亂不可讀像那樣。
最主要的缺點是你添加了一個新的工具依賴項到你的項目中,也因爲你需要用cog section markers來註釋它的用法,它實際上可能比手動編寫小的用法更糟糕。這是值得的,當你需要聲明的大枚舉或很多不可避免的樣板代碼
可能重複: //堆棧溢出。COM /問題/ 5348077/C-宏觀問題的解釋-的逗號 – 2012-02-23 16:06:16
@OliCharlesworth啊),我沒有找到一個在我的搜索。答案似乎有不回答我的問題,準確,但它確實發人深思一些食物。謝謝。 – chrisaycock 2012-02-23 16:09:57
一個較新的問題,有一些優秀的答案:http://stackoverflow.com/questions/13842468/comma-in-cc-macro/13842784#13842784 – jjrv 2014-07-17 05:35:53