#include <iostream>
using namespace std;
class StringNum {
public:
string s;
StringNum() {s = "";}
public:
StringNum(int n) {
s = "";
for (int i=1; i<=n; i++) s += "x";
}
operator int () {
return s.length();
}
StringNum operator + (StringNum v) {
cout << "operator + is called\n";
int len = s.length() + v.s.length();
StringNum res;
for (int i=1;i<=len;i++) res.s += "x";
return res;
}
template <class T>
StringNum operator + (T value) {
return (*this) + StringNum(value);
}
};
template<class T>
StringNum operator + (T value, const StringNum& num) {
cout << "operator + opposite is called\n";
//return value + num; // infinite recursion, of course
// return num + value; // infinite recursion, despite StringNum + <class T> is defined
return num + StringNum(value); // STILL infinite recursion
//return StringNum(num) + value; // correct, output 6
}
int main()
{
StringNum x(4);
cout << (x + 2.5) << "\n"; // StringNum + <class T>, output 6
int res = (2 + x);
cout << res;
return 0;
}
Class StringNum represents an integer number > 0, where length of the string is the number.
StringNum + StringNum
are member functions and work correctly.
StringNum + <class T>
is also a member function and works correctly.
However, for <class T> + StringNum
, it requires a external function. However, the behavior of operator +
is confusing and doesn't make any sense:
template<class T>
StringNum operator + (T value, const StringNum& num) {
cout << "operator + opposite is called\n";
//return value + num; // infinite recursion, of course
// return num + value; // StringNum + <class T>, infinite recursion. Why??
return num + StringNum(value); // STILL infinite recursion
//return StringNum(num) + value; // StringNum + <class T> -> this time it's correct, output 6
}
How is it that num + StringNum(value)
causes infinite recursion, while it should call StringNum + StringNum
? Also, why does num + value
cause infinite recursion, while it should call StringNum + <class T>
? Finally, how does StringNum(num) + value
solve the problem when num
is a StringNum in the first place?
How can I correctly implement commutative operator +
in this case ? Thank you.