关于这
宏定义函数的用法,现在不是特别常见,但是在特殊情况下还是很有用的。
定义如下:
class StringBuilder
{
public:
StringBuilder(const char8_t* str);
virtual ~StringBuilder();
...
virtual StringBuilder& operator<<(const char8_t* value) { return operator+(value); }
virtual StringBuilder& operator<<(int8_t value);
virtual StringBuilder& operator<<(int16_t value);
virtual StringBuilder& operator<<(int32_t value);
virtual StringBuilder& operator<<(int64_t value);
virtual StringBuilder& operator<<(uint8_t value);
virtual StringBuilder& operator<<(uint16_t value);
virtual StringBuilder& operator<<(uint32_t value);
virtual StringBuilder& operator<<(uint64_t value);
virtual StringBuilder& operator<<(double value);
virtual StringBuilder& operator<<(const void * value);
};
基本实现思路如下, (代码十分简洁明了)
#define OPERATOR_IMPL(Type, Formatter) \
StringBuilder& StringBuilder::operator<<(Type value) \
{ \
if ((mSize - mCount) < 64) \
{ \
if (!grow(64)) \
{ \
mCount = 0; \
return *this; \
} \
} \
mCount += blaze_snzprintf(mBuffer + mCount, mSize - mCount, "%"Formatter, value); \
return *this; \
}
OPERATOR_IMPL(int8_t, PRId8);
OPERATOR_IMPL(int16_t, PRIi16);
OPERATOR_IMPL(int32_t, PRIi32);
OPERATOR_IMPL(int64_t, PRId64);
OPERATOR_IMPL(uint8_t, PRIu8);
OPERATOR_IMPL(uint16_t, PRIu16);
OPERATOR_IMPL(uint32_t, PRIu32);
OPERATOR_IMPL(uint64_t, PRIu64);
OPERATOR_IMPL(double, "f");
OPERATOR_IMPL(const void *, "p");
现在回头看看以前的总结http://jacky-dai.javaeye.com/admin/b
logs/868376,从这里可以看出有的时候宏定义函数还是很好用的。