[Home]CPPTM Answers - Exercise 2-5

BOOST WIKI | RecentChanges | Preferences | Page List | Links List

No diff available--this is the first major revision. (minor diff)
 // (by Ariel Badichi)
 #include <iostream>

 #include <boost/type_traits.hpp>

 template<typename T>
 struct return_type
 {
     typedef void type;
 };

 template<typename R>
 struct return_type<R()>
 {
     typedef R type;
 };

 template<typename T>
 struct type_descriptor
 {
     std::ostream & print(std::ostream & out) const
     {
         if (boost::is_volatile<T>::value) {
             typedef typename boost::remove_volatile<T>::type newtype;
             out << "a volatile " << type_descriptor<newtype>();
         } else if (boost::is_const<T>::value) {
             typedef typename boost::remove_const<T>::type newtype;
             out << "a const " << type_descriptor<newtype>();
         } else if (boost::is_pointer<T>::value) {
             typedef typename boost::remove_pointer<T>::type newtype;
             out << "pointer to " << type_descriptor<newtype>();
         } else if (boost::is_reference<T>::value) {
             typedef typename boost::remove_reference<T>::type newtype;
             out << "reference to " << type_descriptor<newtype>();
         } else if (boost::is_array<T>::value) {
             typedef typename boost::remove_bounds<T>::type newtype;
             out << "array of " << type_descriptor<newtype>();
         } else if (boost::is_function<T>::value) {
             typedef typename return_type<T>::type newtype;
             out << "function returning " << type_descriptor<newtype>();
         } else if (boost::is_same<long, T>::value) {
             out << "long";
         } else if (boost::is_same<int, T>::value) {
             out << "int";
         } else if (boost::is_same<short, T>::value) {
             out << "short";
         } else if (boost::is_same<char, T>::value) {
             out << "char";
         } else if (boost::is_same<void, T>::value) {
             out << "void";
         } else {
             out << "unknown";
         }

         return out;
     }
 };

 template<typename T>
 std::ostream & operator<< (std::ostream & out, const type_descriptor<T> & desc)
 {
     return desc.print(out);
 }

 int main()
 {
     std::cout << type_descriptor<int>() << "\n"
               << type_descriptor<char *>() << "\n"
               << type_descriptor<long const * &>() << "\n"
               << type_descriptor<short[10]>() << "\n"
               << type_descriptor<volatile int>() << "\n"
               << type_descriptor<char *(*[])()>() << "\n";

     return 0;
 }

BOOST WIKI | RecentChanges | Preferences | Page List | Links List
Edit text of this page | View other revisions
Last edited March 25, 2005 2:37 pm (diff)
Search:
Disclaimer: This site not officially maintained by Boost Developers