模板隐式转换

4
使用以下代码:
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.

我的问题是:是否有一种方法可以获得这样的隐式复制构造函数,但不必定义它的工作方式?当一个类被创建时默认情况下提供复制、赋值和标准构造函数...如果可能的话,使用模板时也能免费获得隐式转换构造函数将会很好。
我猜这是不可能的,但如果是这样,请问有人能解释一下为什么吗?
谢谢!

将来请尽量只在与C编程语言相关的问题上打上C标签。 - nmichaels
我怀疑编译器是否允许隐式复制 - 毕竟,这些类在继承意义上并不相关。 - Vlad
1个回答

1

你不能让编译器为你生成一个伪复制构造函数模板。为什么?因为MyClass<T>可以是与MyClass<U>完全不同的东西。

这不是我的原始答案。我误解了问题,抱歉


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接