如何“取消引用类型”在C++03?
如何在 C++03 中获取另一种类型的“取消引用类型”?请注意,它可以是其他可取消引用的类型,例如 std::vector
例如,如果我有
template<typename T>
struct MyPointer
{
T p;
??? operator *() { return *p; }
};
,我怎样才能找出用什么来替换 ???
?
(无提升!我想知道如何自己解决。)
How do I get the "dereferenced type" of another type in C++03? Note that it can be other dereferenceable type like std::vector<int>::iterator
.
e.g. if I have
template<typename T>
struct MyPointer
{
T p;
??? operator *() { return *p; }
};
How can I figure out what to replace the ???
with?
(No Boost! I want to know how to figure it out myself.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在一般情况下,你不能。对于原始指针,您可以部分专业化,如其他答案所示 - 自定义智能指针可能具有结果类型的通用 typedef。但是,您无法编写一个可以处理 C++03 中任何指针的函数。
In the general case, you can't. For raw pointers, you can partially specialize as shown in other answers- custom smart pointers may have a common typedef for the result type. However, you cannot write a single function that will cope with any pointer in C++03.
您可以有一个简单的构造,它递归地从给定类型中删除所有指针,如下所示:
下面是内联包装函数,用于递归地从给定指针或非指针类型中找出实际值;
只需将其用作:
在本例中,它会删除给定类型的所有指针,但根据需要,您可以配置
ActualType<>
和ActualValue<>.即使您使用非指针类型声明
MyPointer
,也不会出现任何编译器错误。这是一个针对单个指针且无指针类型的工作演示。
You can have a simple construct which recursively removes all the pointers from a given type as below:
Below is the inline wrapper function to recursively find out the actual value from a given pointer or non-pointer types;
And just use it as:
In this example, it removes all the pointers from a given type, but as per the need you can configure the
ActualType<>
andActualValue<>
. There won't be any compiler error even if you declareMyPointer<>
with a non-pointer type.Here is a working demo for a single pointer and no pointer types.
您可以这样做,并确保模板仅在您传递指针时才会编译:
You can do it like this, and it is ensured that the template will only compile when you pass pointers to it: