Guide
macro expansions
- #name ===> quote as strings “xxx”
- ##name, name ===> xxx
- a ## b ===> concatenate the preceding and following tokens.
#define QUOTE(name) #name
#define CONCAT(x,y) x##y
#define MACRO(name) #name "foo"
#define MACRO2(name) name "foo"
#define MACRO3(name) ##name "foo"
#define CAT(a, ...) a ## __VA_ARGS__
#define IIF(c) CAT(IIF_, c)
#define IIF_0(t, ...) __VA_ARGS__
#define IIF_1(t, ...) t
void macro_demo()
{
QUOTE(test);
CONCAT(test, foo);
MACRO(test);
MACRO2(test);
MACRO3(test);
}
macro function
define
#define SUM(a,b) (a+b)
#define MYDEBUG(...) fprintf(stderr, ##__VA_ARGS__)
usage
int c = SUM(1,2);
MYDEBUG("%d,%d \n",1,2);
with class object
define
class profiler {
public:
profiler(const char* func_name, unsigned int times = 1);
~profiler();
void start();
int stop();
private:
boost::posix_time::ptime pt1;
boost::posix_time::ptime pt2;
const char * m_func_name;
int m_times = 1;
};
#define ONCE_PROFILER() profiler _profiler_instance##__LINE__(__FUNCTION__)
#define BEGIN_PROFILE_ONE(name) profiler _profiler_##name(#name)
#define BEGIN_PROFILE_TIMES(name,times) profiler _profiler_##name(#name,times)
#define BEGIN_PROFILE(name,...) profiler _profiler_##name(#name, ##__VA_ARGS__)
#define END_PROFILE(name) _profiler_##name.stop()
usage
void main()
{
BEGIN_PROFILE(LoadImage);
load_image();
END_PROFILE(LoadImage);
BEGIN_PROFILE_TIMES(ProcessImageTimes, 100);
for(int i=0; i<100;i++){
process_image();
}
END_PROFILE(ProcessImageTimes);
}
Reference
History