When compiling the following:
template <class T>
class Number
{
private:
T num;
public:
Number() {}
Number( T n ) : num(n) {}
operator T() const { return num; }
};
int main()
{
Number<int> n=5;
Number<char> c=4;
int i;
c=int(5);
i=n;
c=n;
return 0;
}
The compiler gets stuck at the third assignment saying there is no match for operator= in c=n. Shouldn’t n get converted to int, which in turn will be assigned to c?
According to the standard, at most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value. Here, you are expecting the compiler to apply the constructor for
Number<char>and the conversion operator forNumber<int>. See: https://stackoverflow.com/a/867804/677131.