如何确定 C++对象是一个 time_t
如何确定 C++ 对象是否是 time_t,而不是定义的整型 time_t?
我特别想模板专门化一个函数,
template <typename T> void myFunction( T val );
template<> void myFunction<time_t>( time_t val );
这样当 time_t 定义为的整数类型被传递时,非专门化的函数就会被调用。
我的 STL 实现将 time_t
定义为 long
,因此 myFunction(42L)
调用 time_t 专门化。我怎样才能防止这种情况发生?
我尝试专门化long
,这会导致编译错误(主体已经被定义)。我还尝试了 rtti,typeid(time_t).name()
返回 "long"
。
我如何区分 time_t
和它定义的整数类型,和/或模板专门化 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有办法阻止这种情况。
在 C++ 中,
typedef
相当于其所有用途的基类型。在编译时,它们是等效的。在运行时,它们是等效的。您可以完全删除
time_t
的定义并将其重新定义为不同的类型,但这会破坏用户代码调用需要正确time_t
的函数的能力。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 propertime_t
.你根本无法得到你想要的东西。
time_t
被定义(至少在 C 标准中)为typedef
(提示是名称的“_t
”部分),其中并没有引入新的类型。您想要区分某人是否调用一个名称或另一个名称,但 C 和 C++ 不允许这样做。You fundamentally can't get what you want.
time_t
is defined (at least in the C standard) as atypedef
(the hint is the "_t
" part of the name), which does not introduce a new type. You want to make a distinction between whether somebody calls the one name or another, but C and C++ don't allow that.