写代码的时候,当发现有很多代码可以用都是相似的,
就忍不住用宏来生成代码。
可是宏也会导致程序可读性没那么好,bug难调。
不知道大神们在编程的时候是怎么使用宏的呢?
宏和模板都是为了减少写代码的量,同时是为了方便将来的修改,比如像C语言中用宏代替数字,修改的时候只改一次。我就很喜欢用宏和模板,写出来的代码很漂亮,同时代码量很少,后期修改维护起来很容易。
比如我现在写的:
namespace Nti { namespace Http { class RequestMethod { ENUMERABLE(RequestMethod , Details::_RequestMethodKey) ENUMERABLE_ITEM(RequestMethod , Get , Details::GET) ENUMERABLE_ITEM(RequestMethod , Post , Details::POST) ENUMERABLE_ITEM(RequestMethod , Head , Details::HEAD) ENUMERABLE_ITEM(RequestMethod , Options , Details::OPTIONS) ENUMERABLE_ITEM(RequestMethod , Put , Details::PUT) ENUMERABLE_ITEM(RequestMethod , Delete , Details::DELETE) ENUMERABLE_ITEM(RequestMethod , Trace , Details::TRACE) ENUMERABLE_ITEM(RequestMethod , Connect , Details::CONNECT) } ; } }
这样一个类写出来,基本上就是几个宏就写完了,微软通常也采用这种方法,你如果看过MFC的代码就知道了
宏和模板都是为了减少写代码的量,同时是为了方便将来的修改,比如像C语言中用宏代替数字,修改的时候只改一次。我就很喜欢用宏和模板,写出来的代码很漂亮,同时代码量很少,后期修改维护起来很容易。
比如我现在写的:
namespace Nti { namespace Http {
class RequestMethod
{
ENUMERABLE(RequestMethod , Details::_RequestMethodKey)
ENUMERABLE_ITEM(RequestMethod , Get , Details::GET)
ENUMERABLE_ITEM(RequestMethod , Post , Details::POST)
ENUMERABLE_ITEM(RequestMethod , Head , Details::HEAD)
ENUMERABLE_ITEM(RequestMethod , Options , Details::OPTIONS)
ENUMERABLE_ITEM(RequestMethod , Put , Details::PUT)
ENUMERABLE_ITEM(RequestMethod , Delete , Details::DELETE)
ENUMERABLE_ITEM(RequestMethod , Trace , Details::TRACE)
ENUMERABLE_ITEM(RequestMethod , Connect , Details::CONNECT)
} ;
} }
这样一个类写出来,基本上就是几个宏就写完了,微软通常也采用这种方法,你如果看过MFC的代码就知道了