Show Lecture.ProxyObjects as a slide show.
This doesn’t work:
double pi() { return 3.14159; } string pi() { return "π"; } int main() { double d = pi(); string s = pi(); cout << d << ' ' << s << '\n'; }
c.cc:2: error: ambiguating new declaration of 'std::__cxx11::string pi()'
The failure is at line 2, not at the point of use. You can’t overload just on the return type.
This doesn’t work, either:
class Foo { public: double pi() { return 3.14159; } string pi() { return "π"; } };
c.cc:4: error: 'std::__cxx11::string main()::Foo::pi()' cannot be overloaded with 'double main()::Foo::pi()'
Same problem.
.pi_double()
and .pi_string()
,
but I would then plunge into depression over the sheer inelegance.
class Dual { public: operator double() const { return 3.14159; } operator string() const { return "π"; } }; Dual pi() { return Dual(); } int main() { double d = pi(); string s = pi(); cout << d << ' ' << s << '\n'; }
3.14159 π
pi()
doesn’t return a number or a string. It returns a
proxy object, which will produce either value, based on context.
class Dual { const double d; const string s; public: Dual(double dd, const string &ss) : d(dd), s(ss) { } operator double() const { return d; } operator string() const { return s; } }; Dual pi() { return Dual(3.14159, "π"); } int main() { double d = pi(); string s = pi(); cout << d << ' ' << s << '\n'; }
3.14159 π
template <typename T, typename U> class Dual { const T t; const U u; public: Dual(const T &tt, const U &uu) : t(tt), u(uu) { } operator T() const { return t; } operator U() const { return u; } }; Dual<double, string> pi() { return Dual<double, string>(3.14159, "π"); } int main() { double d = pi(); string s = pi(); cout << d << ' ' << s << '\n'; }
3.14159 π
template <typename T, typename U> class Dual { const T t; const U u; public: Dual(const T &tt, const U &uu) : t(tt), u(uu) { } operator T() const { return t; } operator U() const { return u; } }; Dual<double, string> pi() { return {3.14159, "π"}; } int main() { double d = pi(); string s = pi(); cout << d << ' ' << s << '\n'; }
3.14159 π