Topic: Determining between classes and built-in types


Author: fjh@munta.cs.mu.OZ.AU (Fergus Henderson)
Date: 1995/10/05
Raw View

"Brett W. Denner" <dennerbw@cliffy.lfwc.lockheed.com> writes:

>Is there a way to identify whether a data type in a template function is a
>class or a built-in type?
>
>For example,
>
>template <class T> void
>func(T var)
>{
>    if ( /* test whether T is a built-in type */ )
>  /* do something based on T being a built-in type */;
>    else
>        /* do something else based on T being a user-define type */;A
>}
>
>Will rtti allow me to test for this?  Is there another way of determing this?

The standard RTTI does not supply this information.
As recently discussed in the thread entitled
"Do we need a standard IsPointer() function?",
you can, at least in theory, use partial template specialization
to do it yourself - although most compilers don't support this yet.

 // unless otherwise specified, a type is not builtin
 template <class T>
 inline bool is_builtin_type() { return false; }

 // all the basic types are builtin
 inline bool is_builtin_type<char>() { return true; }
 inline bool is_builtin_type<int>() { return true; }
 // etc.

 // all pointer types are builtin
 template <class T>
 inline bool is_builtin_type<T*> () { return true; }
 template <class T>
 inline bool is_builtin_type<const T*> () { return true; }
 template <class T>
 inline bool is_builtin_type<volatile T*> () { return true; }
 template <class T>
 inline bool is_builtin_type<const volatile T*> () { return true; }

 // similarly for reference types
 // I guess you also want to handle array types
 // and pointer-to-member types

Then you can use

 if ( is_builtin_type<T>() ) ...

to test whether a type is builtin or not.

--
Fergus Henderson             |  "Australia is the richest country in the world,
fjh@cs.mu.oz.au              |   according to a new system of measuring wealth
http://www.cs.mu.oz.au/~fjh  |   announced by the World Bank yesterday."
PGP: finger fjh@128.250.37.3 |  - Melbourne newspaper "The Age", 18 Sept 1995.

---
[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]