I have this code. In main I want use type conversion, but with using debug I understand that in this line
ob2=(Point2D<double>)ob1;
constructor template <class T1> Point2D(Point2D<T1>& ob) is invoked regardless of explicit before i.e. template <class T1> explicit Point2D(Point2D<T1>& ob) Why does this happen? I expect that operator Point2D<T1>() is invoked.
template <class T>
class Point2D
{
public:
T x;
T y;
Point2D(T _x=0,T _y=0):x(_x),y(_y)
{
}
Point2D(Point2D& ob)
{
x=ob.x;
y=ob.y;
}
template <class T1>
Point2D(Point2D<T1>& ob)
{
x=ob.x;
y=ob.y;
}
template <class T1>
operator Point2D<T1>()
{
return Point2D<T1>(x,y);
}
};
int main()
{
Point2D<int> ob1(10,10);
Point2D<double> ob2(20,20);
ob2=(Point2D<double>)ob1;
return 0;
}
Section
[dcl.init]of the standard specifies that constructors are preferred during initialization:This rule means that user-defined conversion sequences are only considered if no constructor applies.
Casts use the same rule as initialization, see
[expr.static.cast]:and
[expr.cast]:Also note
[class.conv.ctor]: