In C ++ 03, there is no way to implement typeof without using sizeof . The closest useful alternative is to extract the type using a function template that returns the desired type.
template<typename T> struct Type { }; template<typename T> Type<T> makeType(T) { return Type<T>(); } int main() { int i; makeType(2 + 2);
The following method uses function templates in C ++ 03 to extract the type and value of any expression that can be used in a template argument.
template<typename T, T value> struct NonType { }; template<typename T> struct Type { template<T value> static NonType<T, value> makeNonType() { return NonType<T, value>(); } }; template<typename T> Type<T> makeType(T) { return Type<T>(); } #define MAKE_NONTYPE(e) makeType(e).makeNonType<e>() int i; int main() { MAKE_NONTYPE(2 + 2); // NonType<int, 4> MAKE_NONTYPE(&i); // NonType<int*, i> }
The following answer shows the practical use of this method to extract the type and value of a pointer to an expression of a member function: How to enable the functor template to work for both member functions and non-members
source share