Go Premium for a chance to win a PS4. Enter to Win

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 506
  • Last Modified:

Template derivation


I created a template class :

template<class T>
class CBaseT
 T *m_pT;
public :
 T *Get();
 void Set(T *pT);

And I derived a class from it :

class Derived : public CBaseT<char>
 public :
 Derived() {Set("A");} // Correction, instead of: Set('A');

The problem is that I got a link error which says that
the class CBaseT<char> is not found.

My question is : Why is that happened , and how can I
fix it that CBaseT<char> will be found ?

1 Solution
Set('A') passes a const char, but your definition of Set() requires a char*.

You could change the definition to

void Set(T pT);

and it should work.
Or you could simply pass in "A" instead of 'A'.
"A" will be a char * because it creates a string of two characters (A and \0) whereas 'A' is just one char.
>>Why is that happened , and how can I fix it that
>>CBaseT<char> will be found ?

This is most likely happening because you put the implementation for your code in the *.cpp file.

In other words, you have the {void Set(T *pT)} function defined in the *.cpp file.

For template classes you need to define the functions in the header.


Although the current C++ standards say that you can put the functions in the *.cpp file, most compilers do not support this capability.

If you put the code in the *.cpp file, then only code that includes the *.cpp file can declare new types of your template class.

An alternative to this is to put a special forward declaration for each type that you will use for the template class.

The syntax for this is the following:

template CBaseT<char>;

The above forward declaration would be put into the *.cpp file that has your template function defined.
You would have to do this for each type if you want to use this method.

I do not recommend using the above method unless you really have a good reason for keeping the template function definition inside your *.cpp file.

It is far easier to just keep the template function difinition in the *.h header file, and this is the common method used by most programmers for template classes.
MichaelMarommAuthor Commented:
Thank you Axter,
You realy helped me.


Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now