Member templates
Bruce Eckel
Bruce@EckelObjects.com
Wed Nov 25 23:04:00 GMT 1998
This comes (with slight changes) from Andrew Koenig-Barbara Moo "Ruminations
on C++", pp 250-253. I believe it should compile, but it appears that the
member template definition is choking it (this is the 11/22/98 snapshot).
template<class X, class Y> class Comp_base {
public:
virtual Y operator()(X) const = 0;
virtual Comp_base* clone() const = 0;
virtual ~Comp_base() {}
};
template<class F, class G, class X, class Y>
class Comp: public Comp_base<X, Y> {
public:
Comp(F f0, G g0) : f(f0), g(g0) {}
Y operator()(X x) const { return f(g(x)); }
Comp_base<X, Y>* clone() const {
return new Comp(*this);
}
private:
F f;
G g;
};
template<class X, class Y> class Composition {
public:
template<class F, class G> composition(F, G);
Composition(const Composition&);
Composition& operator=(const Composition&);
~Composition();
Y operator() (X) const;
private:
Comp_base<X, Y>* p;
};
template<class X, class Y> template<class F, class G>
Composition<X, Y>::Composition(F f, G g) :
p(new Comp<F, G, X, Y> (f, g)) {}
template<class X, class Y>
Composition<X, Y>::~Composition() { delete p; }
template<class X, class Y>
Composition<X, Y>::Composition(const Composition& c)
: p(c.p->clone()) {}
template<class X, class Y>
Composition& Composition<X, Y>::operator=(const Composition& c) {
if(this != &c) {
delete p;
p = p.clone();
}
return *this;
}
template<class X, class Y>
Y Composition<X, Y>::operator() (X x) const {
return (*p)(x);
}
int f(int) { return 1;}
int g(int) { return 2;}
int h(int) { return 3;}
int main() {
Composition<int, int> fg(f, g);
Composition<int, int> fgh(fg, h);
}
=============================
Bruce Eckel http://www.BruceEckel.com
Contains free electronic books: "Thinking in Java" & "Thinking in C++ 2e"
More information about the Gcc-bugs
mailing list