This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

class member reference to template


Hi!

The following code yields code which produces the 4 lines below
I admit I am not sure whether this is ANSI, but I believe it should ...
(If it ain't ANSI, then the compiler should complain anyway)

output:

This is constructor of Wrap<1A>
This is constructor of Wrap<1B>
B
Illegal instruction

------------------------------------------------------------------
#include <iostream>
#include <typeinfo>

using namespace std;

class Base {
public:
  virtual void DoSomething() { /* overwrite */ }
};

template <class C> class Wrap : public Base {
private:
  C& c_;
public:
  Wrap(C& c) : c_(c) {
    cerr << "This is constructor of Wrap<"
         << typeid(C).name() << ">" << endl;
  }

  void DoSomething() { c_.DoSomething(); }
};


class Help {
private:
  const Base& b_;

public:
  template <class A> Help(A& a) : b_(Wrap<A>(a)) {}

  void DoSomething() { const_cast<Base&>(b_).DoSomething(); }
};




class A {
public:
  void DoSomething() { cerr << "A" << endl; }
};

class B {
public:
  void DoSomething() { cerr << "B" << endl; }
};

int main() {
  A a;
  B b;

  Help aa(a);
  Help bb(b);

  aa.DoSomething();
  bb.DoSomething();
}
--------------------------------------------------------------------



OTH You may use a nested approach which works fine:

#include <iostream>
#include <typeinfo>

using namespace std;

class Help {
  // inner classes start
-----------------------------------------------------
  class Base {
  public:
    virtual void DoSomething() { /* overwrite */ }
  };

  template <class A> class Inner : public Base {
  private:
    A& a_;
  public:
    Inner(A& a) : a_(a) {
      cerr << "This is constructor of Inner<"
           << typeid(A).name() << ">" << endl;
    }

    void DoSomething() { a_.DoSomething(); }
  };
  // inner classes stop
------------------------------------------------------


  const Base& b_;

public:
  template <class A> Help(A& a) : b_(Inner<A>(a)) {}

  void DoSomething() { const_cast<Base&>(b_).DoSomething(); }
};




class A {
public:
  void DoSomething() { cerr << "A" << endl; }
};

class B {
public:
  void DoSomething() { cerr << "B" << endl; }
};

int main() {
  A a;
  B b;

  Help aa(a);
  aa.DoSomething();

  Help bb(b);
  bb.DoSomething();
}



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]