模板隐式转换

Template Implicit Conversions

本文关键字:转换      更新时间:2023-10-16

加上代码:

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.

我的问题是:是否有一种方法可以获得像这样的隐式复制构造函数,但不必定义它是如何工作的?默认情况下,创建类时都提供了复制、赋值和标准构造函数…在使用模板时,如果可能的话,也可以免费获得隐式转换构造函数,那就太好了。

我猜这是不可能的,但是如果是这样的话,有人能给我解释一下为什么吗?

谢谢!

你不能让编译器为你生成一个伪copy-constructor-template。为什么?因为MyClass<T>可以是与MyClass<U>

完全不同的

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