Search code examples
c++templatestypedefrttitemplate-specialization

How to determine if a C++ object is a time_t


How can I determine if a C++ object is a time_t, as opposed to the integral type time_t is defined as?

I specifically want to template specialize a function,

template <typename T> void myFunction( T val );
template<>            void myFunction<time_t>( time_t val );

such that the unspecialized function gets called when the integral type which time_t is defined as gets passed.

My STL implementation defines time_t as long, so myFunction(42L) calls the time_t specialization. How can I prevent this?

I tried specializing long, which results in a compile error (body has already been defined). I also tried the rtti, typeid(time_t).name() returns "long".

How can I discriminate between time_t and the integral type it is defined as, and/or template specialize time_t such that its integral type does not get passed to the specialization?

A way to do it with templates would be preferable, but I would accept any solution, run-time or compile-time.


Solution

  • There is no way to prevent this.

    In C++, a typedef is equivalent to its base type for all purposes. At compile time, they are equivalent. At run time, they are equivalent.

    You could remove the definition of time_t entirely and redefine it as a different type, but that would break the user code's ability to call a function expecting a proper time_t.