如何确定 C++对象是一个 time_t

发布于 2025-01-06 08:01:55 字数 632 浏览 2 评论 0原文

如何确定 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空‖城人不在 2025-01-13 08:01:55

没有办法阻止这种情况。

在 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 proper time_t.

烟柳画桥 2025-01-13 08:01:55

你根本无法得到你想要的东西。 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 a typedef (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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文