Templates in C++ - Class Templates
(Page 3 of 4 )
The same can be done for a class. So let's create it.
template< class T>
class ClassTemp
{
public:
ClassTemp();
~ClassTemp();
T& member();
const T& member() const;
private:
T m_member;
typename T::C(y);
typedef char C;
ClassTemp::C d;
};
template<class T>
T& ClassTemp::member()
{
return m_member;
}
template<class T>
const T& ClassTemp::member() const
{
return m_member;
}
The code snippet presented above reserves more information about classes. First of all, you have to implement the functions in the header file also. So you can't use the usual method of making the declarations in the header and writing the implementation in the source files (cpp files). All of this must be within a single file.
Is this a drawback of the compiler? It seems weird to me that even Microsoft failed to implement this. Until they do, remember to write the declarations and the definitions in the same file.
Template functions and classes usually take up more space; they are larger, but for the sake of programming, they aren't less efficient compared to one written for a specific type. Moreover, if you do it right, they may make the difference because they can be compiled as inline functions. Heaven on earth!
Moreover, there is an additional key you should know about it. It's something that occurs when the compiler fails to decide whether you're declaring a function or a type within the parameters of the function. If this is the case, you can explicitly specify that it's a key with the typename keyword. This should be used each time you have a qualified name that refers to a type and depends on a template parameter. Only use the keyword typename in template declarations and definitions.
To more easily understand the issue, let's revisit the declared class. You see, should we write just ClassTemp::C then the ClassTemp is ill-formed, or more exactly it depends upon a parameter. To bypass this limitation, write the typename before the expression to indicate that it points to a type.
Also, this is the situation in the case of the ClassTemp::x(y). Now this can be interpreted as we call a function of the ClassTemp with parameter y or as we declare a y variable of ClassTemp::x. The compiler will take the function interpretation, but if we want it any other way, we can just add the typename keyword beforehand.
Next: Template Specialization >>
More C++ Articles
More By Gabor Bernat