Question when creating a template class

Asked 2 years ago, Updated 2 years ago, 22 views

// TestClass.h
template <typename T>
class TestClass
{
   TestClass();
}
// TestClass.cpp
#include <TestClass.h>

template <typename T>
TestClass<T>::TestClass()
{
}

We're trying to implement the template class by dividing the header file and the source file An error is coming out. Is it impossible to implement the template class separately in this way?

c++

2022-09-21 15:31

1 Answers

From the point of view, it is recommended that the implementation of class templets be written in the header file.

The class template is not of type, so you can instantiate it by entering the template factor. This instantiated type is called template class.

TestClass<int> t;

For example, in the above code, TestClass is a class template, TestClass<int> is an instantiated template class, and t is an instance name of this class.

When instantiating a class template, the compiler goes through the process of replacing the template parameter (T for questions) with the entered template factor. To replace, of course, you need to know the contents of the template. Therefore, the code that defines the class template must exist before the location where the class template is instantiated.

This does not mean that the template definition must exist in the header file. This means that you should know the definition of the template from the preprocessed results in the cpp file from which the template is instantiated. Therefore, if a template definition exists in a different cpp file, an error occurs because the contents are unknown in the cpp file that instantiates the template.

Starting with C++11, external template allows you to define and use template classes in other cpps. However, there is a limitation in this case because you have to create them all by template factor.


2022-09-21 15:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.