CS253: Software Development with C++

Spring 2019

Proxy Objects

Show Lecture.ProxyObjects as a slide show.

CS253 Proxy Objects

The problem

Overloading Functions

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.

Overloading Methods

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.

Pouting

Solution

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.

More General Solution

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 π

Even More General Solution

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 π

Slightly Prettier Solution

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 π

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2019-05-31T14:20

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building