问题描述
我觉得这个问题曾被问过,但我无法在SO上找到,也找不到Google上有用的东西。也许协变不是我寻找的词,但这个概念非常类似于协变的返回类型的函数,所以我认为这可能是正确的。这是我想做的,它给我一个编译器错误:
I feel like this one has been asked before, but I'm unable to find it on SO, nor can I find anything useful on Google. Maybe "covariant" isn't the word I'm looking for, but this concept is very similar to covariant return types on functions, so I think it's probably correct. Here's what I want to do and it gives me a compiler error:
class Base;
class Derived : public Base;
SmartPtr<Derived> d = new Derived;
SmartPtr<Base> b = d; // compiler error
假设这些类完全充实...我想你得到了想法。由于一些不清楚的原因,它不能将 SmartPtr< Derived>
转换为 SmartPtr< Base>
我记得这是正常的C + +和许多其他语言,虽然目前我不记得为什么。
Assume those classes are fully fleshed out... I think you get the idea. It can't convert a SmartPtr<Derived>
into a SmartPtr<Base>
for some unclear reason. I recall that this is normal in C++ and many other languages, though at the moment I can't remember why.
我的根问题是:什么是最好的方法执行此赋值操作?目前,我将指针从 SmartPtr
中拉出,明确地将其转换为基本类型,然后将其包装到新的 SmartPtr
类型(注意,这不是泄漏的资源,因为我们自己的 SmartPtr
类使用侵入式引用计数)。这很长,很杂乱,特别是当我需要将另一个对象...任何快捷键包装 SmartPtr
?
My root question is: what is the best way to perform this assignment operation? Currently, I'm pulling the pointer out of the SmartPtr
, explicitly upcasting it to the base type, then wrapping it in a new SmartPtr
of the appropriate type (note that this is not leaking resources because our home-grown SmartPtr
class uses intrusive reference counting). That's long and messy, especially when I then need to wrap the SmartPtr
in yet another object... any shortcuts?
推荐答案
复制构造函数和赋值操作符应该能够获取不同类型的SmartPtr,并尝试将指针从一个复制到另一个。如果类型不兼容,编译器会抱怨,如果它们兼容,您已经解决了您的问题。类似这样:
Both the copy constructor and the assignment operator should be able to take a SmartPtr of a different type and attempt to copy the pointer from one to the other. If the types aren't compatible, the compiler will complain, and if they are compatible, you've solved your problem. Something like this:
template<class Type> class SmartPtr
{
....
template<class OtherType> SmartPtr(const SmartPtr<OtherType> &blah) // same logic as the SmartPtr<Type> copy constructor
template<class OtherType> SmartPtr<Type> &operator=(const SmartPtr<OtherType> &blah) // same logic as the SmartPtr<Type> assignment operator
};
这篇关于C ++协变模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!