加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 模板隐式转换

发布时间:2020-12-16 06:57:08 所属栏目:百科 来源:网络整理
导读:随着代码: template typename Tclass MyClass{ public: MyClass(const MyClass other) { //Explicit,types must both match; } template typename U MyClass(const MyClassU other) { //Implicit,types can copy across if assignable. //? Is there a way
随着代码:

template <typename T>
class MyClass
{
    public:

        MyClass(const MyClass& other)
        {
            //Explicit,types must both match;
        }    

        template <typename U>
        MyClass(const MyClass<U>& other)
        {
            //Implicit,types can copy across if assignable.
            //<?> Is there a way to make this automatically happen for memberwise
            //copying without having to define the contents of this function?

            this->value = other.getValue();
        }

    privte:

        T value;
};

以下情况属实:

MyClass<float> a;

MyClass<float> b = a; //Calls explicit constructor which would have been auto-generated.

MyClass<int> c;

MyClass<float> d = c; //Calls implicit constructor which would not have been auto gen.

我的问题是:有没有办法获得这样的隐式复制构造函数,但不必定义它是如何工作的?默认情况下创建类时,都会提供复制,赋值和标准构造函数…如果可能的话,在使用模板时,能够获得隐式转换构造函数也是很好的.

我猜它不可能,但有人可以解释为什么那是我的话,如果是这样的话?

谢谢!

解决方法

您不能让编译器为您生成伪拷贝构造函数模板.为什么?因为MyClass< T>可以是与MyClass完全不同的< U>

这不是我原来的答案.对不起,我误解了这个问题

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读