Topic: member template questions


Author: Mika Niemi <Mika.Niemi@lmf.ericsson.se>
Date: Sun, 4 Mar 2001 04:14:53 GMT
Raw View
I have a couple of questions about member templates. I am using Stroustrup's
C++ textbook, which leaves some stuff about them unclear.


1. I understand why it is difficult to have a virtual member template, but
why is it forbidden to override a virtual function with a member template
instance? A code example:

        // two unrelated types with identical interfaces
        class Type1{
        public:
          void f() { std::cout<<"called Type1::f()\n";};
        };
        class Type2{
        public:
          void f() { std::cout<<"called Type2::f()\n";};
        };

        class Base {
        public:
          virtual g(Type1*) = 0;
          virtual g(Type2*) = 0;
        };

        //use member template to override two base functions
        class Derived : public Base {
        public:
          template <class T> void g(T* val){ val->f();};
        };

Is this a complication with overloading rules or implicit type conversions,
or something like that?


2. What is the correct syntax for explicit instantiation of a member
template? Since a class is just a special case of namespace, I am
assuming it is the same as would be for a template function in a
namespace, i.e.:

        class Derived : public Base {
        public:
          template <class T> void g(T* val){ val->f();};
          template void g(Type1*);
          template void g(Type2*);
        };

or

        template void Derived::g(Type1*);
        template void Derived::g(Type2*);


3. What is the correct syntax for taking a pointer to member of a
member template instance? And does declaring or using a pointer to
member of a member template instance implicitly instantiate that
specialization?


        class Type3{
        public:
          void f() { std::cout<<"called Type3::f()\n";};
        };

        typedef void (Derived::* pointer_to_g)(Type3*);

        Derived* a = new Derived();

        pointer_to_g b = &Derived::g;

        Type3* c = new Type3();

        a->*b(c);


4. Is it possible to have non-type, or default, template arguments
in member templates? i.e.:

        class Derived : public Base {
        public:
          template <class T, unsigned int Times = 1> void g(T* val){
            for(int i = 0;i<Times;i++)val->f();
          };
        };

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.research.att.com/~austern/csc/faq.html                ]
[ Note that the FAQ URL has changed!  Please update your bookmarks.     ]