Template Implicit Conversions
With the code:
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;
};
The following cases would be true:
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.
My question is: is there a way to get an implicit copy constructor like this, but not have to define how it works? Copy, assignment, and standard constructors are all provided when a class is created by default... it would be nice to be able to get an implicit conversion constructor as well for free if possible when using templates.
I'm guessing its not possible but can someone explain why that is to me if that is the case?
Thanks!
You can't make the compiler generate a pseudo-copy-constructor-template for you. Why? Because MyClass<T>
can be something entirely different from MyClass<U>
This isn't my original answer. I had misunderstood the question, sorry
精彩评论