Original Post
Hi All,
I am trying to use c++ templates to differentiate memory handling between int,float,short,char types,
and char*, char[1..n].
It works fine for primitive types e.g
CBasicData, CBasicData, CBasicData...
It also works for CBasicData, but not for
CBasicData, CBasicData, CBasicData.
I need to generalize behviour for all string and char[] implementations.
How can I generalize it to work for any type of char[N], where N > 0 && < 1000.
Any help will be appreciated.
Thanks ,
Caz.
[source lang="cpp"]
// use this for char,int,float, and all primitive types
template < typename t > // Primary template
class CBasicData
{
public:
union Data
{
char m_cMemory[sizeof(t)];
t m_kValue;
}mData;
t GetValue() const { return mData.m_kValue; }
const char* GetMemory() { return mData.m_cMemory; }
void SetValue(const t& kValue ) { mData.m_kValue = kValue ; }
unsigned GetSize() { return sizeof(mData.m_kValue); }
};
// use this for char*, char[1..n], strings
// and or char[4]
// for char[9]
// for char[38]
// for char[2]
template< >
class CBasicData < char[2] > // Secondary template. This only works for char[2], but should be same for char[1..n]
{
std::string m_strValue;
public:
const char* GetMemory() { m_strValue.c_str(); }
const std::string& GetValue() const { return m_strValue; }
void SetValue(const std::string& rstrValue ) { m_strValue = rstrValue ; }
unsigned GetSize() { return m_strValue.length(); }
};
[/source]
I am trying to use c++ templates to differentiate memory handling between int,float,short,char types,
and char*, char[1..n].
It works fine for primitive types e.g
CBasicData
It also works for CBasicData
CBasicData
I need to generalize behviour for all string and char[] implementations.
How can I generalize it to work for any type of char[N], where N > 0 && < 1000.
Any help will be appreciated.
Thanks ,
Caz.
[source lang="cpp"]
// use this for char,int,float, and all primitive types
template < typename t > // Primary template
class CBasicData
{
public:
union Data
{
char m_cMemory[sizeof(t)];
t m_kValue;
}mData;
t GetValue() const { return mData.m_kValue; }
const char* GetMemory() { return mData.m_cMemory; }
void SetValue(const t& kValue ) { mData.m_kValue = kValue ; }
unsigned GetSize() { return sizeof(mData.m_kValue); }
};
// use this for char*, char[1..n], strings
// and or char[4]
// for char[9]
// for char[38]
// for char[2]
template< >
class CBasicData < char[2] > // Secondary template. This only works for char[2], but should be same for char[1..n]
{
std::string m_strValue;
public:
const char* GetMemory() { m_strValue.c_str(); }
const std::string& GetValue() const { return m_strValue; }
void SetValue(const std::string& rstrValue ) { m_strValue = rstrValue ; }
unsigned GetSize() { return m_strValue.length(); }
};
[/source]