Skip to content

Instantly share code, notes, and snippets.

@carlos-urena
Created November 1, 2019 09:54
Show Gist options
  • Save carlos-urena/c28b7dd1cdc180ab379fc17d9c8e5796 to your computer and use it in GitHub Desktop.
Save carlos-urena/c28b7dd1cdc180ab379fc17d9c8e5796 to your computer and use it in GitHub Desktop.
An attempt to do limited compile time reflection in C++
// it would be better to use 'std::is_array', 'std::is_reference' 'std::is_integral', and such....
#include <iostream>
#include <sstream>
#include <string>
#define TD1( T, d ) \
template<> class TypeDescriptor< T > \
{ public: static std::string text() \
{ \
return std::string( d ) ; \
} \
};
template<typename T> class TypeDescriptor
{ public: static inline std::string text()
{
return std::string("unknown") ;
}
};
template<typename T> class TypeDescriptor<T *>
{ public: static std::string text()
{
return std::string("pointer to ") + TypeDescriptor<T>::text() ;
}
};
template<typename T, unsigned long N> class TypeDescriptor< T [N] >
{ public: static std::string text()
{
return std::string("fixed size array with ") + std::to_string( N ) + " values of type " + TypeDescriptor<T>::text() ;
}
};
template<typename T> class TypeDescriptor< T & >
{ public: static std::string text()
{
return std::string("reference to ") + TypeDescriptor<T>::text() ;
}
};
template<typename T> class TypeDescriptor< T [] >
{ public: static std::string text()
{
return std::string("pointer to array of ") + TypeDescriptor<T>::text() ;
}
};
TD1( char, "char" )
TD1( short, "short" )
TD1( int, "int" )
TD1( long, "long" )
TD1( unsigned char, "unsigned char" )
TD1( unsigned short, "unsigned short" )
TD1( unsigned int, "unsigned int" )
TD1( unsigned long, "unsigned long" )
TD1( float, "float" )
TD1( double, "double" )
TD1( long double, "long double" )
template<typename T>
std::string DescribeTypeOf( T & v )
{
return TypeDescriptor<T>::text() ;
}
using namespace std ;
void f( int e[] )
{
cout << "'e' is a " << DescribeTypeOf(e) << endl ;
}
void g( int x )
{
cout << "'e' is a " << DescribeTypeOf(e) << endl ;
}
int main()
{
int * a ;
cout << "'a' is a " << DescribeTypeOf(a) << endl ;
int b[3] ;
cout << "'b' is a " << DescribeTypeOf(b) << endl ;
unsigned cc = 3 ;
unsigned & c = cc ;
cout << "'c' is a " << DescribeTypeOf(c) << endl ;
int d[3][4] ;
cout << "'d' is a " << DescribeTypeOf(d) << endl ;
f(b);
cout << "'g' is a " << DescribeTypeOf(g) << endl ;
cout << "test: " << TypeDescriptor< int &>::text() << endl ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment