【发布时间】:2012-08-14 14:30:25
【问题描述】:
我有一个 C++03 应用程序,它的类包含一个类型的单个实例,我试图在派生类型的持有者和基类型的持有者之间进行转换。例如:
class B { public: virtual ~B() { }; };
class A : public B { };
template< typename T >
class Container
{
public:
explicit Container( T* obj ) : obj_( obj ) { };
Container( const Container< T >& ref ) : obj_( ref.obj_ ) { };
template< typename U > operator Container< U >() {
return Container< U >( obj_ );
};
private:
T* obj_;
};
这很好用:
int main()
{
Container< A > a_ref( new A() );
Container< B > b_ref = a_ref;
return 0;
}
这给了我错误invalid initialization of reference of type ‘Container<B>&’ from expression of type ‘Container<A>’:
void Foo( Container< B >& cb ) { }
int main()
{
Container< A > a_ref( new A() );
Foo( a_ref );
return 0;
}
这给了我错误error: invalid initialization of non-const reference of type ‘Container<B>&’ from a temporary of type ‘Container<B>’L
int main()
{
Container< A > a_ref( new A() );
Foo( static_cast< Container< B > >( a_ref ) );
return 0;
}
如何将Container< A > 类型传递给需要Container< B > 类型的函数?我需要先复制对象吗?
【问题讨论】:
-
是的,您必须复印一份。即使 A 是从 B 派生的,一个容器也不是从另一个容器派生的。它们是完全不同的类型。
-
a_ref不是...参考(参考)。
标签: c++ templates constructor type-conversion