Make sense. Thanks.
On Feb 28, 12:27*pm, Victor Bazarov <v.baza...@comcast.invalid> wrote:
> On 2/28/2011 11:56 AM, syang8 wrote:
>
> > I'd like to ask the reason the following code works. Original, I
> > expected that there is going to be a "function redefinition" error.
> > Could anyone tell me whether this is a compiler specific (I am using
> > GNU g++ 4.3.4) issue or this actually conforms to the C++ standard? I
> > appreciate.
>
> > A function f is defined in a template class A. Class B inherited from
> > A<int> *redefines the function f in A<int>. The output shows that the
> > definition f in A<int> *is actually changed, while the other instance
> > of the template, e.g. A<float>, remains untouched.
>
> What you have here is called a "specialization" of the template member.
> * Read about it.
>
>
>
>
>
>
>
>
>
>
>
> > //===================================
> > #include<iostream>
>
> > template<class T>
> > class A
> > {
> > public:
>
> > * * *typedef A<T> *BaseT;
> > * * *int f();
> > };
>
> > template<class T>
> > int A<T>::f()
> > {
> > * * *return 1;
> > }
>
> > class B : public A<int>
> > {
> > };
>
> > template<>
> > int
> > B::BaseT::f()
> > {
> > * * *return 3;
> > }
>
> > int main()
> > {
> > * * *A<int> *a1;
> > * * *A<float> *a2;
> > * * *B b;
> > * * *std::cout<< *a1.f()<< *std::endl;
> > * * *std::cout<< *a2.f()<< *std::endl;
> > * * *std::cout<< *b.f()<< *std::endl;
> > }
>
> > // ======================================
> > // The output of the program is
> > // 3
> > // 1
> > // 3
>
> V
> --
> I do not respond to top-posted replies, please don't ask
|