C ++模板类型转换带衍生 [英] C++ Templates type casting with derivates

查看:122
本文介绍了C ++模板类型转换带衍生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个泛型转换为另一个,例如:

I'm trying to cast from one generic to another, say:

myClass<MoreAbstract> anItem = myclass<DerivateFromMoreAbstract> anotherObject;

或执行

aFunction(anotherObject); // myclass<DerivateFromMoreAbstract> anotherObject 

其中aFunction签名

where aFunction signature is

aFunction(myClass<MoreAbstract> item);

事实上,myClass实际上是在线找到的shared_ptr的简化实现。我想知道是否有任何方式,我可以切换从一个指针类型到另一个被封装。

In fact, myClass is actually a simplified implementation of shared_ptr I found online. I'm wondering if there's any way I can actually switch from one pointer type to another being encapsulated.

有没有办法做这样的转换?

Is there any way to do such casting? If so, what would be the correct way to do it?

如果它可以帮助任何人,VC ++给我这个错误:

If it helps anyone, VC++ gives me this error:

Error 1 error C2440: 'type cast' : cannot convert from 'myClass<T>' to 'myClass<T>'


推荐答案

您不能静态强制转换,因为它们是不兼容的类型。有时您可以创建一个运算符来强制类型

You can't static cast, as they are incompatible types. You can sometimes create an operator to coerce the type instead

#include <iostream>

class A { };

class B : public A { };


template<typename T>
struct holder {
    T* value;

    holder ( T*value ) : value ( value ) { }

    template < typename U > // class T : public U
    operator holder<U> () const
    {
        return holder<U>( value );
    }
};


int main ()
{
    using namespace std;

    B   b;

    holder<B>   hb ( &b );
    holder<A>   ha  = hb;

    cout << boolalpha;

    cout << ( hb.value == ha.value ) << endl;

    return 0;
}

这是否是一个有意义的操作,而是取决于模板类的语义 - 如果 aFunction 可以将任何内容放入处理程序,则不希望更具体的对象被突变。因此,你以某种方式复制,要么使用强制运算符,要么使用模板复制构造函数和赋值。 (强制是较少的代码,但如果不使用引用参数,可能会导致创建更多的对象)

Whether this is a meaningful operation rather depends on the semantic of the template class - if the aFunction can put anything into the handler, you don't want the more specific object being mutated. Hence you copy somehow, either with a coercion operator or with a template copy constructor and assignment. ( the coercion is less code but might result in more objects being created if you don't use reference parameters )

这篇关于C ++模板类型转换带衍生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆