#ifndef __TO_STRING_H__
#define __TO_STRING_H__
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
class ToAString
{
public:
ToAString(int v)
{
sprintf(m_buffer, "%i", v);
}
ToAString(unsigned int v)
{
sprintf(m_buffer, "%u", v);
}
ToAString(long v)
{
sprintf(m_buffer, "%ld", v);
}
ToAString(unsigned long v)
{
sprintf(m_buffer, "%lu", v);
}
ToAString(bool v)
{
if(v)
strcpy(m_buffer, "true");
else
strcpy(m_buffer, "false");
}
ToAString(float v)
{
sprintf(m_buffer, "%f", v);
}
ToAString(double v)
{
sprintf(m_buffer, "%f", v);
}
ToAString(long long v)
{
sprintf(m_buffer, "%lld", v);
}
public:
//operator的另外一种用法,定义强制类型转换,该函数无返回值,但是必须返回对应类型的值,即必须出现return语句。
inline operator const char*() const
{
return m_buffer;
}
private:
char m_buffer[64];
};
class ToWString
{
public:
ToWString(int v)
{
swprintf(m_buffer, sizeof(m_buffer)/sizeof(m_buffer[0]), L"%i", v);
}
ToWString(unsigned int v)
{
swprintf(m_buffer, sizeof(m_buffer)/sizeof(m_buffer[0]), L"%u", v);
}
ToWString(unsigned long v)
{
swprintf(m_buffer, sizeof(m_buffer)/sizeof(m_buffer[0]), L"%lu", v);
}
ToWString(bool v)
{
if(v)
wcscpy(m_buffer, L"true");
else
wcscpy(m_buffer, L"false");
}
ToWString(float v)
{
swprintf(m_buffer, sizeof(m_buffer)/sizeof(m_buffer[0]), L"%f", v);
}
ToWString(double v)
{
swprintf(m_buffer, sizeof(m_buffer)/sizeof(m_buffer[0]), L"%f", v);
}
ToWString(long long v)
{
swprintf(m_buffer, sizeof(m_buffer)/sizeof(m_buffer[0]), L"%lli", v);
}
inline operator const wchar_t*() const
{
return m_buffer;
}
private:
wchar_t m_buffer[64];
};
#if defined(UNICODE) || defined(_UNICODE)
typedef ToWString ToString;
#else
typedef ToAString ToString;
#endif
//隐式类型转换的一种实现
//在需要用到int的地方,也可以传ToInt过去
class ToInt
{
public:
ToInt(const char* p, int radix = 10) // radix: 2, 8, 10, 16
{
if('0' == *p)
{
radix = ('x'==p[1] || 'X'==p[1]) ? 16 : 8;
}
switch(radix)
{
case 2:
m_data = str2int_radix2(p);
break;
case 8:
m_data = str2int_radix8(p);
break;
case 10:
m_data = atoi(p);
break;
case 16:
m_data = str2int_radix16(p);
break;
}
}
inline int str2int_radix2(const char* p)
{
int v = 0;
for(; p; ++p)
{
if('0'!=*p && '1'!=*p)
break;
v = v*2 + (*p - '0');
}
return v;
}
inline int str2int_radix8(const char* p)
{
int v = 0;
for(; p; ++p)
{
if('0'>*p || '7'<*p)
break;
v = v*8 + (*p - '0');
}
return v;
}
inline int str2int_radix16(const char* p)
{
int v = 0;
for(; p; ++p)
{
if('0'<=*p && '9'>=*p)
{
v = v*16 + (*p - '0');
}
else if('a'<=*p && 'f'>=*p)
{
v = v*16 + (*p - 'a' + 10);
}
else if('A'<=*p && 'F'>=*p)
{
v = v*16 + (*p - 'A' + 10);
}
else
{
break;
}
}
return v;
}
public:
//operator的另外一种用法,定义强制类型转换,该函数无返回值,但是必须返回对应类型的值,即必须出现return语句。
inline operator int() const
{
return m_data;
}
private:
int m_data;
};
#endif //