In article <3f***********************@dread16.news.tele.dk> ,
"Lasse Skyum" <no spam> wrote:
Hi All,
Is it possible to detect (at compile-time) if an item is a basic type (int,
float, double,...) or an instance of a class/struct?
I'm thinking something like: (obviosly this isn't working...)
template<typename T>
CMyFileClass::Serialize(T &x)
{
#if IS_BASIC_TYPE(T)
// handle basic type
#else
// handle a class inherited from my CSerializable class
#endif
}
You might be interested in the type traits library at boost:
http://www.boost.org/libs/type_traits/index.htm
This library has been submitted for standardization and accepted into
the first library technical report:
http://std.dkuug.dk/jtc1/sc22/wg21/d...2003/n1424.htm
A close facsimile of this lib has shipped with Metrowerks CodeWarrior
for the past 3 years. It lives in namespace Metrowerks in the header
<msl_utility>.
These libs might be used like:
#include <msl_utility>
using namespace Metrowerks;
struct CSerializable {};
template <class T>
struct CMyFileClass
{
void Serialize(T& x);
private:
void Serialize(T& x, int2type<false>);
void Serialize(T& x, int2type<true>);
};
template<typename T>
inline
void
CMyFileClass<T>::Serialize(T &x)
{
Serialize(x, int2type<is_arithmetic<T>::value>());
}
template<typename T>
void
CMyFileClass<T>::Serialize(T &x, int2type<true>)
{
// handle basic type
}
template<typename T>
void
CMyFileClass<T>::Serialize(T &x, int2type<false>)
{
compile_assert<is_convertible<T, CSerializable>::value>
must_be_convertible_to_CSerializable;
// handle a class inherited from my CSerializable class
}
I wrote this using the Metrowerks tools so that I could check it before
I posted. The boost or std::tr1 interface would be very close.
-Howard