Redefintion of a function in template class

S

syang8

Hi all,

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.

//===================================
#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

Victor Bazarov

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top